3

我一直在尝试围绕@property装饰器,我想我明白了,但我很想知道 @property (和 builtin property)修改了哪些魔术方法。它只是__get__and __set__,还是也可以调用__getattr__and ?? ?__setattr____getattribute____setattribute__

据我了解,@someproperty 将修改__get__,@ someproperty.setter 将修改__set__, @someproperty.deleter 将修改,__del__但我怀疑我对此的看法过于简化。

我一直无法找到此信息,并且我整天都在搜索有关房产的信息,因此希望有人可以为我提供一些启示。非常感谢链接和示例。

编辑:我错误地说“调用”而不是“修改”,我知道@property 会修改魔术方法。我只是因为永远盯着这个而筋疲力尽......感谢您的纠正。

4

2 回答 2

3

@property不调用任何这些。它定义了它们的工作方式。访问该属性然后调用__get____set____delete__

class Foo(object):
    @property
    def x(self):
        return 4

    # If the class statement stopped here, Foo.x would have a __get__ method
    # that calls the x function we just defined, and its __set__ and __delete__
    # methods would raise errors.

    @x.setter
    def x(self, value):
        pass

    # If the class statement stopped here, Foo.x would have usable __get__ and
    # __set__ methods, and its __delete__ method would raise an error.

    @x.deleter
    def x(self):
        pass

# Now Foo.x has usable __get__, __set__, and __delete__ methods.

bar = Foo()
bar.x      # Calls __get__
bar.x = 4  # Calls __set__
del bar.x  # Calls __delete__
于 2013-09-05T23:43:18.027 回答
2

标题问题的答案:__get__(),__set__()__delete__(),

您将在此处找到有关财产内部运作的更多详细信息,正如 dm03514 所指出的,在此处

于 2013-09-05T23:33:20.743 回答