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

时间:2019-05-12 14:22:53

标签: python python-3.x properties

python的新手,想知道是否可以在另一个属性的设置器中以编程方式设置类属性?例如:在下面的代码中,我想基于days_off设置器中提供的值设置years属性。

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

1 个答案:

答案 0 :(得分:1)

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

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