I need to make a bunch of class variables and I would like to do it by looping through a list like that:
vars=('tx','ty','tz') #plus plenty more class Foo(): for v in vars: setattr(no_idea_what_should_go_here,v,0)
is it possible? I don't want to make them for an instance (using self in the __init__) but as class variables.
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
Use a Dictionary to Create a Dynamic Variable Name in Python It is written with curly brackets {} . In addition to this, dictionaries cannot have any duplicates. A dictionary has both a key and value, so it is easy to create a dynamic variable name using dictionaries.
Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.
First, extract the class body as string. Second, create a class dictionary for the class namespace. Third, execute the class body to fill up the class dictionary. Finally, create a new instance of type using the above type() constructor.
You can run the insertion code immediately after a class is created:
class Foo(): ... vars=('tx', 'ty', 'tz') # plus plenty more for v in vars: setattr(Foo, v, 0)
Also, you can dynamically store the variable while the class is being created:
class Bar: locals()['tx'] = 'texas'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With