在 Python 中使用 Property 的删除器装饰器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1912229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
deleter decorator using Property in Python
提问by
I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google.
我正在玩 Python 中的属性,我想知道这个 @propertyName.deleter 装饰器是如何工作的。我可能遗漏了一些东西,我找不到谷歌的明确答案。
What I would like to achieve is when this deleterbehavior is called, I can trigger other actions (e.g: using my 3d application SDK).
我想要实现的是,当调用此删除器行为时,我可以触发其他操作(例如:使用我的 3d 应用程序 SDK)。
For now just a simple print() doesn't seem to get triggered.
现在只是一个简单的 print() 似乎没有被触发。
Is deleterfired when I delete the property using del(instance.property)?
为删除器发射时使用我删除属性德尔(instance.property) ?
Otherwise, how can I achieve this?
否则,我怎么能做到这一点?
class M():
def __init__(self):
self._m = None
@property
def mmm(self):
return self._m
@mmm.setter
def mmm(self, val):
self._m = val
@mmm.deleter
def mmm(self):
print('deleting') # Not printing
del(self._m)
if __name__ == '__main__':
i = M()
i.mmm = 150
print(i.mmm)
del(i.mmm)
print(i.mmm)
Thank you very much (:
非常感谢你 (:
采纳答案by unutbu
Make M a new-style class:
使 M 成为一个新式类:
class M(object):
See http://www.python.org/download/releases/2.2.3/descrintro/#property:
请参阅http://www.python.org/download/releases/2.2.3/descrintro/#property:
Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its dictwithout calling the property's set method, and after that, the property's get method won't be called either. (You could override setattrto fix this, but it would be prohibitively expensive.)
属性不适用于经典类,但尝试此操作时不会出现明显错误。您的 get 方法将被调用,因此它似乎可以工作,但是在分配属性时,经典类实例将简单地在其dict 中设置值 而不调用属性的 set 方法,之后,将不会调用属性的 get 方法任何一个。(你可以覆盖 setattr来解决这个问题,但它会非常昂贵。)
回答by Alex Martelli
In Python 3 you WOULD see the print
's result -- and then an AttributeError for the last print (because _m
has disappeared). You may be using Python 2.6, in which case you need to change the class
clause to class M(object):
to make M
new-style, and then you'll get the same behavior as in Python 3.
在 Python 3 中,你会看到print
's 结果——然后是最后一次打印的 AttributeError (因为_m
已经消失了)。您可以使用Python 2.6,在这种情况下,您需要更改class
条款class M(object):
作出M
新的样式,然后你会得到相同的行为在Python 3。