[英]Questions about details of @property in Python
假设我有一个如下课程:
class MyClass(object):
def __init__(self, value=None):
self.attr = value
@property
def attr(self):
# This acts as a getter?
# Let's call the function "attr_1" as alias
return self.__attr
@attr.setter
def attr(self, value):
# This acts as a setter?
# Let's call the function "attr_2" as alias
self.__attr = value
inst = MyClass(1)
我阅读了有关描述符的文档,并研究了property
类的实现。
据我所知,当我键入inst.attr
,会发生以下情况:
attr
(其别名为attr_1
),并且attr
现在是property
类的实例,它是一个数据描述符 。 type(inst).__dict__['attr'].__get__(inst, type(inst))
。 attr.__get__(inst, type(inst))
调用attr.fget(inst)
,其中fget()
实际上是attr(self)
(“原始” attr_1
函数)。 attr.fget(inst)
返回inst.__attr
。 这是第一个问题:类MyClass
没有属性__attr
,那么如何在步骤3中解释inst.__attr
呢?
类似地,在模拟的setter中,Python如何找到inst.__attr
来分配value
?
而一个简单的问题:因为property
是一类,为什么不Property
,而不是property
?
您的问题实际上与属性及其作为数据描述符的工作方式没有直接关系。 这就是Python伪造标记为以两个下划线开头的私有属性的方式。
>>> inst.__attr
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
inst.__attr
AttributeError: 'MyClass' object has no attribute '__attr'
考虑到您使用带有单个下划线的内部变量编写了代码(通常习惯上说, 您不应该碰这个,但我不会强制执行,后果自负 ):
>>> class MyClass2(object):
def __init__(self, value=None):
self.attr = value
@property
def attr(self):
# This acts as a getter?
# Let's call the function "attr_1" as alias
return self._attr
@attr.setter
def attr(self, value):
# This acts as a setter?
# Let's call the function "attr_2" as alias
self._attr = value
>>> inst2 = MyClass2(1)
>>> inst2._attr
1
您可以通过窥视对象的__dict__
来了解窍门
>>> inst2.__dict__
{'_attr': 1}
>>> inst.__dict__
{'_MyClass__attr': 1}
只是更多说服您,这与属性无关:
>>> class OtherClass(object):
def __init__(self, value):
self.__attr = value
def get_attr(self):
return self.__attr
def set_attr(self, value):
self.__attr = value
>>> other_inst = OtherClass(1)
>>> other_inst.get_attr()
1
>>> other_inst.__attr
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
other_inst.__attr
AttributeError: 'OtherClass' object has no attribute '__attr'
>>> other_inst.__dict__
{'_OtherClass__attr': 1}
>>> other_inst._OtherClass__attr
1
>>> other_inst._OtherClass__attr = 24
>>> other_inst.get_attr()
24
>>> inst._MyClass__attr = 23
>>> inst.attr
23
关于您的最后一个问题,我只是认为Python中没有这样的约定,即类必须以大写开头。 property
不是孤立的情况( datetime
, itemgetter
, csv.reader
等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.