combomethod
访问时不会创建方法对象,而是专门包装的函数。与方法一样,每次访问都会创建一个新对象,在这种情况下是一个新的函数对象。
class A:
def __init__(self):
self.data = 'instance'
@combomethod
def foo(param):
if isinstance(param, A):
print("This is an " + param.data + " method.")
elif param is A:
print("This is a class method.")
>>> a = A()
>>> A.foo
<function foo at 0x00CFE810>
>>> a.foo
<function foo at 0x00CFE858>
>>> A.foo()
This is a class method.
>>> a.foo()
This is an instance method.
每次访问都是新的:
>>> A.foo is A.foo
False
>>> a.foo is a.foo
False
foo
真的_wrapper
是变相了:
>>> A.foo.__code__.co_name
'_wrapper'
当从一个类调用时,闭包有 obj == None (注意这里的 'self' 指的是组合方法,它引用了 中的原始函数对象self.method
):
>>> print(*zip(A.foo.__code__.co_freevars, A.foo.__closure__), sep='\n')
('obj', <cell at 0x011983F0: NoneType object at 0x1E1DF8F4>)
('self', <cell at 0x01198530: combomethod object at 0x00D29630>)
('objtype', <cell at 0x00D29D10: type object at 0x01196858>)
当作为实例的属性调用时,obj 是实例:
>>> print(*zip(a.foo.__code__.co_freevars, a.foo.__closure__), sep='\n')
('obj', <cell at 0x01198570: A object at 0x00D29FD0>)
('self', <cell at 0x01198530: combomethod object at 0x00D29630>)
('objtype', <cell at 0x00D29D10: type object at 0x01196858>)
这是存储在组合方法中的原始函数:
>>> A.foo.__closure__[1].cell_contents.method
<function foo at 0x00D1CB70>
>>> A.foo.__closure__[1].cell_contents.method.__code__.co_name
'foo'
_wrapper
self.method
给定 obj 的值,将类或实例作为第一个参数执行:
if obj is not None:
return self.method(obj, *args, **kwargs)
else:
return self.method(objtype, *args, **kwargs)