这是我想出的东西,它的行为就像该方法存在一样。
首先让我们确定一件事:你无法区分__getattr__
if attr
来自函数调用或“属性访问”,因为类方法是一个属性你们班的。因此,即使有人不打算调用该方法,也可以访问该方法,如下所示:
class Test:
def method(self):
print "Hi, I am method"
>> t = Test()
>> t.method # just access the method "as an attribute"
<bound method Test.method of <__main__.Test instance at 0x10a970c68>>
>> t.method() # actually call the method
Hi, I am method
因此,我能想到的最接近的是这种行为:
创建一个 A 类,使得:
- 当我们尝试访问该类中已存在的属性/方法时,表现正常并仅返回请求的属性/方法。
- 当我们尝试访问类定义中不存在的内容时,请将其视为类方法,并为所有此类方法提供 1 个全局处理程序。
我将首先编写类定义,然后展示访问不存在的方法的行为与访问存在的方法完全相同,无论您只是访问它还是实际调用它。
类定义:
class A(object):
def __init__(self):
self.x = 1 # set some attribute
def __getattr__(self,attr):
try:
return super(A, self).__getattr__(attr)
except AttributeError:
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.im_func.func_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.im_func.func_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.im_func.func_name
print "My arguments are: " + str(args)
print "My keyword arguments are: " + str(kwargs)
我添加了方法real_method
只是这样我就有了类中实际存在的东西来将其行为与“想象的方法”的行为进行比较
结果如下:
>> a = A()
>> # First let's try simple access (no method call)
>> a.real_method # The method that is actually defined in the class
<bound method A.real_method of <test.A object at 0x10a9784d0>>
>> a.imaginary_method # Some method that is not defined
<bound method A.imaginary_method of <test.A object at 0x10a9784d0>>
>> # Now let's try to call each of these methods
>> a.real_method(1, 2, x=3, y=4)
I am a method that you actually defined
My name is real_method
My arguments are: (1, 2)
My keyword arguments are: {'y': 4, 'x': 3}
>> 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: {'y': 4, 'x': 3}
>> # Now let's try to access the x attribute, just to make sure that 'regular' attribute access works fine as well
>> a.x
1