当我试图让类装饰器和方法装饰器很好地一起玩时,我遇到了这种行为.从本质上讲,方法装饰器会将某些方法标记为特殊的一些虚拟值,并且类装饰器将在之后出现并稍后填充该值.这是一个简化的例子
>>> class cow:
>>> def moo(self):
>>> print 'mooo'
>>> moo.thing = 10
>>>
>>> cow.moo.thing
10
>>> cow().moo.thing
10
>>> cow.moo.thing = 5
AttributeError: 'instancemethod' object has no attribute 'thing'
>>> cow().moo.thing = 5
AttributeError: 'instancemethod' object has no attribute 'thing'
>>> cow.moo.__func__.thing = 5
>>> cow.moo.thing
5
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么cow.moo.thing = 5不起作用,即使cow.moo.thing很清楚地给我10?为什么cow.moo.__func__.thing = 5有效?我不知道它为什么会这样,但是随机摆弄dir(cow.moo)列表中的东西试图让它起作用突然间,我不明白为什么.
在下面,setattr第一次调用成功,但在第二次调用失败,有:
AttributeError: 'method' object has no attribute 'i'
Run Code Online (Sandbox Code Playgroud)
为什么会这样,有没有办法在方法上设置属性,使其只存在于一个实例上,而不是存在于每个类的实例中?
class c:
def m(self):
print(type(c.m))
setattr(c.m, 'i', 0)
print(type(self.m))
setattr(self.m, 'i', 0)
Run Code Online (Sandbox Code Playgroud)
Python 3.2.2