使用 @property.getter 在 Python 中的属性 [英] Property in Python with @property.getter
问题描述
我对以下代码有一个有趣的行为:
I have an intresting behaviour for the following code:
class MyClass:
def __init__(self):
self.abc = 10
@property
def age(self):
return self.abc
@age.getter
def age(self):
return self.abc + 10
@age.setter
def age(self, value):
self.abc = value
obj = MyClass()
print(obj.age)
obj.age = 12
print(obj.age)
obj.age = 11
print(obj.age)
我有以下结果:
20
12
11
有人可以解释这种行为吗?
Can somebody explain this behaviour ?
推荐答案
在旧样式类(如果您在 Python 2
上执行时就是您的)分配 obj.age =11
将覆盖"描述符.请参阅新课程与经典课程:
On old style classes (which yours is if you're executing on Python 2
) the assignment obj.age = 11
will 'override' the descriptor. See New Class vs Classic Class:
New Style 类可以使用描述符(包括 __slots__
),而 Old Style 类不能.
New Style classes can use descriptors (including
__slots__
), and Old Style classes cannot.
您可以在 Python 3
上实际执行它并使其正确执行,或者,如果您需要一个在 Python 2 和 3 中表现相似的解决方案,从 object
继承> 并把它变成一个新的样式类:
You could either actually execute this on Python 3
and get it executing correctly, or, if you need a solution that behaves similarly in Python 2 and 3, inherit from object
and make it into a New Style Class:
class MyClass(object):
# body as is
obj = MyClass()
print(obj.age) # 20
obj.age = 12
print(obj.age) # 22
obj.age = 11
print(obj.age) # 21
这篇关于使用 @property.getter 在 Python 中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!