大家好。请帮我弄清楚。这是代码:
class Person:
def __init__(self):
self.age = 0
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self.__age = value
t = Person()
t.age = 12
print(t.age) # 12
它工作正常,但让我困惑的是:该属性Person
被称为age
,并且 getters 和 setters 与 交互__age
。我明白__
它被替换为类名,结果是_Person__age
。实际上,代码中发生的是这样的情况:
print(dir(t))
# ['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age']
但是,如果没有皮屑,我会收到错误:
class Person:
def __init__(self):
self.age = 0
@property
def age(self):
return self.age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self.age = value
t = Person()
t.age = 12
print(t.age)
File "main.py", line 47, in age
if value < 0:
RecursionError: maximum recursion depth exceeded in comparison
几个问题:
如果它们相同,为什么我们需要一个带有下划线的属性:
t.age = 12
print(t.age) # 12
print(t._Person__age) # 12
它只vars()
输出{'_Person__age': 12}
- 为什么我会收到没有下划线的错误?
先感谢您