a d中的事件链

2024-04-25 14:09:30 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个客户deleter属性和实例本身的类:

class Hello:
    def __init__(self):
        self._is_open = None
    @property
    def is_open(self):
        return self._is_open
    @is_open.deleter
    def is_open(self):
        print("Using custom deleter!")
        del self._is_open
    def __delattr__(self, attr):
        print ('Deleting attr %s' % attr)
        super().__delattr__(attr)

并称之为:

>>> hello = Hello()
>>> del hello.is_open
Deleting attr is_open
Using custom deleter!
Deleting attr _is_open

看起来它首先调用is_open上的__delattr__,然后调用@is_open.deleter,然后调用_is_open上的__delattr__。为什么删除程序的事件链是这样工作的?你知道吗


Tags: selfhello客户isdefcustomopenattr
1条回答
网友
1楼 · 发布于 2024-04-25 14:09:30

Python propertiesdescriptors。它们通过descriptor protocol实现。你知道吗

datamodel钩子^{}优先于描述符协议。因此,如果您定义了一个定制的__delattr__方法,那么将优先调用属性deleter。你知道吗

事实上,它是__delattr__的默认实现,如果需要,它将去调用描述符,您可以通过注释掉以super开头的行来验证这一点(您应该看到属性deleter现在根本不会被调用)。你知道吗

有了这个推理,你就可以理解这样的一系列事件:

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"第二次。你知道吗

相关问题 更多 >