【问题标题】:Is there a simple way of assigning instance variables in a Python class?有没有在 Python 类中分配实例变量的简单方法?
【发布时间】:2017-11-22 20:51:09
【问题描述】:

在 Python 2.7 中定义一个类时,您将变量输入到 init() 函数中,然后使用例如 self.x 将这些变量分配给实例变量

class NewClass(object): 
  def __init__(self, x, y):      
    self.x = x                    
    self.y = y

如果使用大量变量,有没有办法简化这个过程,即不必显式定义每个实例变量?

或者是否有充分的理由明确定义它们?

【问题讨论】:

  • 当然,但无论如何您可能都应该明确定义它们。此外,如果你真的得到一堆变量,这会变得很痛苦,那么可能是时候问自己“这些数据应该放在一个容器中吗?”
  • 对我来说这看起来很简单。任何你可能改变的东西只会让事情变得复杂。
  • collections.namedtuple 可能是@quamrana 的意思,虽然它是标准库的一部分,而不是内置的。
  • 如果这是 python 3,那么 SimpleNamespace docs.python.org/3.6/library/types.html#types.SimpleNamespace 就足够了。否则请查看 Alex Martelli 的 Bunch Class code.activestate.com/recipes/…

标签: python python-2.7


【解决方案1】:

如果你想要不可变的东西,collections.namedtuple 很有用:

>>> from collections import namedtuple
>>> NewClass = namedtuple('NewClass', 'x y')
>>> obj = NewClass(x=10, y=14)

>>> obj
NewClass(x=10, y=14)

【讨论】:

    【解决方案2】:

    你可以使用__dict__:

    class NewClass:
        def __init__(self, *args):
            self.headers = ["var{}".format(i+1) for i in range(len(args))]#optional, can use an list of variable names you are expecting
            for a, b in zip(self.headers, args):
                self.__dict__[a] = b
    

    【讨论】:

      【解决方案3】:
      class NewClass(object): 
        def __init__(self, **kwargs):
          self.validate(kwargs) # optional      
          self.__dict__.update(kwargs)
      

      但整个想法有点臭

      您还可以拥有一个带有可接受的 kwargs 键的静态集,validate 将检查通过 kwargs 是否包含该集的子集

      【讨论】:

      • 这更简洁,但我认为它更简单。
      • 非常很臭。
      猜你喜欢
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多