我一直在试图围绕@property
装饰者,我想我明白了,但我很好奇知道哪些魔术方法@property(以及内置property
)修改。它只是__get__
和__set__
,还是__getattr__
和__setattr__
也可以调用? __getattribute__
? __setattribute__
?
据我了解,@ someproperty将修改__get__
,@ someproperty.setter将修改__set__
,@ someproperty.deleter将修改__del__
但我怀疑我有对此有一个过于简化的观点。
我一直无法找到这些信息,而且我一直在寻找有关房产的信息,所以希望有人可以为我提供一些信息。链接和示例非常感谢。
编辑:我错误地说“打电话”而不是“修改”,我知道@property会修改魔法。我只是因为永远盯着这个而疲惫不堪......感谢你的纠正。
答案 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)