创建动态 class 属性(不是实例属性)
Creating dynamic class attributes (not instance ones)
有什么方法可以动态创建 class 属性吗?
class MyClass:
attr_one = 'Same_string_with_just_different_value_one'
attr_two = 'Same_string_with_just_different_value_two'
attr_three = 'Same_string_with_just_different_value_three'
[...]
我试过像这样重载 __new__
:
class MyClass:
def __new__(cls, *args, **kwargs):
map_attr_to_value = {
'one': 'value_one',
'two': 'value_two',
'three': 'value_three',
[...]
}
for attr, value in map_attr_to_value.items():
setattr(cls, f"attr_{attr}", f"Same_string_with_just_different_{value}")
return super(MyClass, cls).__new__(cls, *args, **kwargs)
但这对我不起作用,因为 MyClass 从未被实例化,__new__
也从未被调用。我什至不知道这是否真的可能。
谢谢,最诚挚的问候。
您可以使用 type 动态创建 class。参数是 classname, superclasses, attributedict
:
map_attr_to_value = {
'one': 'value_one',
'two': 'value_two',
'three': 'value_three',
}
A = type(
"A", (),
{f"attr_{attr}": value
for attr, value in map_attr_to_value.items()}
)
print(A)
print(A.attr_one)
输出:
<class '__main__.A'>
value_one
有什么方法可以动态创建 class 属性吗?
class MyClass:
attr_one = 'Same_string_with_just_different_value_one'
attr_two = 'Same_string_with_just_different_value_two'
attr_three = 'Same_string_with_just_different_value_three'
[...]
我试过像这样重载 __new__
:
class MyClass:
def __new__(cls, *args, **kwargs):
map_attr_to_value = {
'one': 'value_one',
'two': 'value_two',
'three': 'value_three',
[...]
}
for attr, value in map_attr_to_value.items():
setattr(cls, f"attr_{attr}", f"Same_string_with_just_different_{value}")
return super(MyClass, cls).__new__(cls, *args, **kwargs)
但这对我不起作用,因为 MyClass 从未被实例化,__new__
也从未被调用。我什至不知道这是否真的可能。
谢谢,最诚挚的问候。
您可以使用 type 动态创建 class。参数是 classname, superclasses, attributedict
:
map_attr_to_value = {
'one': 'value_one',
'two': 'value_two',
'three': 'value_three',
}
A = type(
"A", (),
{f"attr_{attr}": value
for attr, value in map_attr_to_value.items()}
)
print(A)
print(A.attr_one)
输出:
<class '__main__.A'>
value_one