开发者

A property's `fdel` method is not invoked when `__delattr__` is overridden

开发者 https://www.devze.com 2023-03-21 20:58 出处:网络
I have a class like this, in which I have declared a property x, and overridden __delattr__: class B(object):

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__.

0

精彩评论

暂无评论...
验证码 换一张
取 消