【发布时间】:2019-05-12 14:22:52
【问题描述】:
python 新手,想知道是否可以在另一个属性的 setter 中以编程方式设置类属性?例如:在下面的代码中,我想根据years setter 中提供的值设置days_off 属性。
class Employee:
def __init__(self, years, days_off=20):
print('initializing')
self.years = years
self.days_off = days_off
def __str__(self):
return f'employee with {self.years} years'
@property
def years(self):
return self._years
@years.setter
def years(self, years):
if 9 < years and years < 20:
print('condition 1 hit')
self.days_off = 25
elif years > 20:
print('condition 2 hit')
self.days_off = 30
self._years = years
test_employee = Employee(7)
other_test_employee = Employee(17)
yet_another = Employee(27)
print(test_employee.days_off) # 20
print(other_test_employee.days_off) # 20, should be 25
print(yet_another.days_off) # 20, should be 30
【问题讨论】:
-
是的,你可以。这就是自定义设置器的用途
-
您没有得到预期结果的原因是您首先设置了
years,然后适当地设置了days_off,但随后您立即用原始值覆盖了它。
标签: python python-3.x properties