【问题标题】:Is it bad practice to call setter properties as your _init_ method definition? [closed]调用 setter 属性作为 _init_ 方法定义是不好的做法吗? [关闭]
【发布时间】:2020-08-18 22:35:26
【问题描述】:

我在几个案例中发现 - 对于某些类属性 - 我的 __init__ 定义与我的 @attribute.setter 完全相似到令人讨厌的程度,激励示例:

class Eg:
   __init__(self, att):
      if #correct type and form
         #do some more checks/formatting
         self._att = att

   @property
   def att(self):
      return self._att

   @att.setter
   def att(self, att):
      if #correct type and form
         #do some more checks/formatting
         self._att = att

我的问题是,如果简单地调用对象初始化的 setter 是否有问题?一个例子:

class Eg:
   __init__(self, att):
      self.att = att

   @property
   def att(self):
      return self._att

   @att.setter
   def att(self, att):
      if #correct type and form
         #do some more checks/formatting
         self._att = att

非常感谢

【问题讨论】:

  • 我会说这是的做法。您可能希望在 __init__ 中应用与其他地方相同的验证,并且在 __init__ 和 setter 中重复验证代码是没有意义的。

标签: python class properties


【解决方案1】:

属性的最大好处之一是可以在不破坏现有接口的情况下引入它。也就是说,如果你从

class Eg:
    def __init__(self, att):
        self.att = att

后来决定att必须是一个正整数,你不必改变你现有的__init__:你只需在类中添加一个属性:

class Eg:
    def __init__(self, att):
        self.att = att

    @property
    def att(self):
        return self._att

    @att.setter
    def att(self, value):
        if value <= 0:
            raise ValueError("att must be a positive integer")
        self._att = value

考虑到这一点,我想说您应该__init__ 中使用setter。 __init__ 内的赋值不是某种特殊情况。

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2015-01-22
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多