【问题标题】:Setting class attributes using a loop inside constructor使用构造函数内的循环设置类属性
【发布时间】:2019-06-25 11:06:54
【问题描述】:

我有一个简单的类(Python 3.6):

class MyClass:
    id: int
    a: int
    b: int
    c: int

我希望在使用循环实例化时设置类属性,例如:

class MyClass:
    def __init__(self, id):
        self.id = id
        for attr in ['a', 'b', 'c']:
            # put something in "self.attr", e.g. something like: self.attr = 1
    id: int
    a: int
    b: int
    c: int

我为什么要这样做?

  1. 列表很长

  2. 我正在使用外部嵌套字典 d 实例化 一些 值,其中 id 作为键,{'a': 1, 'b': 2, 'c': 3} 作为值

所以真的是这样的:

class MyClass:
    def __init__(self, id, d):
        self.id = id
        for attr in ['a', 'b', 'c']:
            # put d[id][attr] in "self.attr", e.g. something like: self.attr = d[id][attr]
    id: int
    a: int
    b: int
    c: int

Adding class attributes using a for loop in Python 是一个类似的问题,但不完全相同;我对在实例化类时循环属性特别感兴趣,即在 __init()__ 构造函数中。

【问题讨论】:

标签: python class constructor


【解决方案1】:

您可以将要设置的属性放在类变量中,然后使用setattr 循环遍历它们:

class Potato:

    _attributes = ['a', 'b', 'c']

    def __init__(self, id, d):
        for attribute in _attributes:
            setattr(self, attribute, d[id][attribute])

【讨论】:

    【解决方案2】:

    您可以在self 上使用setattr

    class MyClass:
        def __init__(self, id, d):
            self.id = id
            for attr in ['a', 'b', 'c']:
                setattr(self, attr, d[id][attr])
    
    
    d = {"123": {'a': 1, 'b': 2, 'c': 3}}
    instance = MyClass("123", d)
    
    print(instance.a)
    print(instance.b)
    print(instance.c)
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      相关资源
      最近更新 更多