class character():
class personalized:
def __init__(self, name, age, height, width, hair_color, eye_color):
# I want to do this
for attr in personalized:
personalized.attr = attr
#instead of this
personalized.name = name
personalized.age = age
personalized.height = height
如果我使用的类有很多属性,我不想每次都把它设置为一个变量,因为它会占用很多空间。有没有一种方法可以像我上面写的那样,但实际上是有效的。本质上,我不知道如何从__init__
函数中检索属性
您可以使用
__set__(..)
函数(https://docs.python.org/3/howto/descriptor.html),但我不建议这样做,因为:使用^{} 和^{} 可以做您想做的事情,但是如果使用Python 3.7+,我建议使用dataclasses和另一个答案一样
vars()
返回局部变量字典。在__init__
的顶部,字典包含self
和作为键的任何参数及其值setattr()
将在对象上设置属性值输出:
我建议为此使用dataclasses。在您的情况下,您只需添加:
这将使用自分配属性为您自动构造一个init
相关问题 更多 >
编程相关推荐