@property触摸的魔术方法

时间:2013-09-05 23:31:18

标签: python python-2.7

我一直在试图围绕@property装饰者,我想我明白了,但我很好奇知道哪些魔术方法@property(以及内置property)修改。它只是__get____set__,还是__getattr____setattr__也可以调用? __getattribute____setattribute__

据我了解,@ someproperty将修改__get__,@ someproperty.setter将修改__set__,@ someproperty.deleter将修改__del__但我怀疑我有对此有一个过于简化的观点。

我一直无法找到这些信息,而且我一直在寻找有关房产的信息,所以希望有人可以为我提供一些信息。链接和示例非常感谢。

编辑:我错误地说“打电话”而不是“修改”,我知道@property会修改魔法。我只是因为永远盯着这个而疲惫不堪......感谢你的纠正。

2 个答案:

答案 0 :(得分: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__

答案 1 :(得分:2)

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

您可以找到有关属性here的内部工作方式的更多详细信息,并且正如dm03514所指出的,here