问题描述
当试图让类装饰器和方法装饰器一起很好地玩时,我遇到了这种情况.本质上,方法装饰器会将某些方法标记为特殊方法,并带有一些虚拟值,而类装饰器将在之后出现,然后再填充该值.这是一个简化的示例
I bumped into this behaviour when trying to get class-decorators and method-decorators to play nicely together. Essentially, the method decorators would flag some of the methods as special with some dummy value, and the class decorator would come by after and fill in the value later. This is a simplified example
>>> 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
即使cow.moo.thing
清楚地给了我10个,有人知道为什么cow.moo.thing = 5
不起作用吗?为什么cow.moo.__func__.thing = 5
起作用?我不知道为什么会这么做,但是随机摆弄dir(cow.moo)
列表中的东西试图使某些东西正常工作,我突然不知道为什么.
Does anyone know why cow.moo.thing = 5
does not work, even though cow.moo.thing
quite clearly gives me 10? And why cow.moo.__func__.thing = 5
works? I have no idea why it does, but in randomly fiddling with stuff in the dir(cow.moo)
list trying to get something to work it suddenly did, and i have no idea why.
推荐答案
对于属性查找,Python会自动为您使用实例方法附带的实函数.
For attribute lookup, Python is automatically using the real function attached to the instance method for you.
对于属性设置,不是.
尽管您都使用.
运算符,但它们还是两个独立的操作,具体取决于您在语句的哪一侧.
They are two separate operations depending on which side of the statement you're on, even though they both use the .
operator.
当您访问实例方法的__func__
时,您是在手动访问实际具有moo
属性的实函数.
When you access an instance method's __func__
, you're manually accessing the real function that actually has the moo
attribute.
在Python 3中,这将按您希望的/预期的那样工作,因为方法基本上只是函数.
In Python 3 this will work as you would like / expect as methods are basically just functions.
这篇关于在Python中将属性添加到实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!