【发布时间】: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
我为什么要这样做?
列表很长
我正在使用外部嵌套字典
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()__ 构造函数中。
【问题讨论】:
-
如果您可以升级到 3.7+,请参阅 docs.python.org/3/library/dataclasses.html
标签: python class constructor