Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create class variable dynamically in python

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.

like image 685
pawel Avatar asked Nov 29 '11 08:11

pawel


People also ask

How do you make a class dynamic in Python?

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.

How do you define a variable dynamically in Python?

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.

How do you assign a class variable in Python?

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.

How do you create a class type in Python?

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.


1 Answers

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' 
like image 196
Raymond Hettinger Avatar answered Oct 09 '22 01:10

Raymond Hettinger