Can class attributes be set dynamically?
Something like this:
class MyConstants:
GLOBAL_VAR = 'actual_attr_name'
class MyStrings:
setattr(cls, MyConstants.GLOBAL_VAR, None)
I wish to automate setting a number of class attributes, for which I don't know/want to hardcode their names... instead fetch them from another class. The snipped above returns
NameError: name 'cls' is not defined
Two ways to do this:
Use locals:
>>> class Foo:
... locals()['dynamic_value'] = 42
...
>>> Foo.dynamic_value
42
But the above isn't really guaranteed to work.
So best is probably to use:
>>> class Foo:
... pass
...
>>> setattr(Foo, 'dynamic_value', 42)
>>> Foo.dynamic_value
42
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.