I am trying to write a class that will catch any generic function call, then try some operations with it.
As an example, I try to use the answer to a similar question from here.
However, it throws a AttributeError: 'method' object has no attribute '__name__'
error when I try to change the method's name by assigning the __name__
attribute.
The code I am using, adapted from the example above is:
class A():
def __init__(self):
self.x = 1 # set some attribute
def __getattr__(self,attr):
return self.__get_global_handler(attr)
def __get_global_handler(self, name):
# Do anything that you need to do before simulating the method call
handler = self.__global_handler
handler.__name__ = name # Change the method's name
return handler
def __global_handler(self, *args, **kwargs):
# Do something with these arguments
print("I am an imaginary method with name %s" % self.__global_handler.__name__)
print("My arguments are: " + str(args))
print("My keyword arguments are: " + str(kwargs))
def real_method(self, *args, **kwargs):
print("I am a method that you actually defined")
print("My name is %s" % self.real_method.__name__)
print("My arguments are: " + str(args))
print("My keyword arguments are: " + str(kwargs))
It works fine if I comment the line that change the method's name (handler.__name__ = name # Change the method's name
):
>>> a.imaginary_method
<bound method A.__global_handler of <__main__.A object at 0x00000150E64FC2B0>>
>>> a.imaginary_method(1, 2, x=3, y=4)
I am an imaginary method with name __global_handler
My arguments are: (1, 2)
My keyword arguments are: {'x': 3, 'y': 4}
However, if I uncomment the line (to force the name change), I get:
>>> a.imaginary_method
[...]
AttributeError: 'method' object has no attribute '__name__'
What I expected to get was something like:
>>> a.imaginary_method
<bound method A.imaginary_method of <__main__.A object at 0x00000150E64FC2B0>>
>>> a.imaginary_method(1, 2, x=3, y=4)
I am an imaginary method with name imaginary_method
My arguments are: (1, 2)
My keyword arguments are: {'x': 3, 'y': 4}
So, is there a way to change the method's name on the fly like that? Thanks a lot!