Python属性是描述符。它们是通过描述符协议实现的。
数据模型挂钩__delattr__
优先于描述符协议。因此,如果您定义了自定义__delattr__
方法,则将优先调用该方法而不是属性删除器。
事实上,它的默认实现__delattr__
将在必要时调用描述符,您可以通过注释掉开头的行来验证这一点super
(您应该看到现在根本不会调用属性删除器)。
有了这个推理,你就可以理解这样的事件链:
Deleting attr is_open
# the del statement `del hello.is_open` is directly invoking Hello.__delattr__,
# passing in attr="is_open" as argument
# Now, the implementation of `Hello.__delattr__` calls
# `super().__delattr__(attr)`, passing along the argument attr="is_open", which
# then invokes a descriptor for that attribute (i.e. the function
# `Hello.is_open.fdel` is about to be called)
Using custom deleter!
# This comes from within the property (`Hello.is_open`) deleter.
Deleting attr _is_open
# The implementation of the `is_open` deleter actually uses another del
# statement, i.e. `del self._is_open`. This invokes again `Hello.__delattr__`,
# passing attr="_is_open" as an argument. However, this time there is no
# descriptor with the name `_is_open` present so an attribute gets deleted from
# the instance namespace instead. Note that the attribute `self._is_open` was
# there in `self.__dict__` already because it gets created during the __init__
# method when `hello = Hello()` is executed.
重要的是要注意__delattr__
第一次和第二次收到不同的论点:"is_open"
第一次然后"_is_open"
第二次。