I have a class like this, in which I have declared a property x
, and overridden __delattr__
:
class B(object):
def __init__(self, x):
self._x = x
def _get_x(self):
return self._x
开发者_如何学JAVA def _set_x(self, x):
self._x = x
def _del_x(self):
print '_del_x'
x = property(_get_x, _set_x, _del_x)
def __delattr__(self, name):
print '__del_attr__'
Now when I run
b = B(1)
del b.x
Only __del_attr__
get invoked, anybody knows why and how to solve this problem?
You have to call the __delattr__
of your ancestor to achieve this correctly.
class B(object):
.....
def __delattr__(self, name):
print '__del_attr__'
super(B, self).__delattr__(name) # explicit call to ancestor (not automatic in python)
And then running :
b = B(1)
del b.x
Will output:
__del_attr__
_del_x
_del_x
is called from the default __del_attr__
. But since you have overridden __del_attr__
, the onus is on you to call _del_x
from inside your __del_attr__
.
精彩评论