【问题标题】:Is it possible to set other attributes in a @property setter in python是否可以在python的@property setter中设置其他属性
【发布时间】: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


【解决方案1】:

正如@Daniel Roseman 在他的评论中提到的那样,首先在设置years 的值时设置days_off 的值,然后将其替换为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

【讨论】:

  • 感谢您的回答和示例!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2021-01-11
  • 2014-10-01
  • 1970-01-01
  • 2011-08-06
相关资源
最近更新 更多