gpt4 book ai didi

python - 是否可以在python中的@property setter中设置其他属性

转载 作者:行者123 更新时间:2023-12-01 07:53:03 24 4
gpt4 key购买 nike

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

最佳答案

正如 @Daniel Roseman 在他的评论中提到的,首先在设置 years 的值时设置 days_off 的值,然后将其替换为 20,因为这是您在 self.years =years 之后执行的下一个作业。为了获得正确的结果,您需要在为 years 赋值之前为 days_off 赋值。因此,您的构造函数应如下所示:

def __init__(self, years, days_off=20):
print('initializing')
self.days_off = days_off
self.years = years

再次运行,将返回正确的结果:

initializing
initializing
condition 1 hit
initializing
condition 2 hit
20
25
30

关于python - 是否可以在python中的@property setter中设置其他属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com