Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically access class properties in Python?

Tags:

python

class

Let's say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:

class MyClass:     def __init__(self):         self.name = None         self.text = None  myclass = MyClass() myclass.name = 'My name' 

But, what if a write a function that takes a class as parameter and I would like to assign some values to the public properties of that class dynamically - that is via variables and loops (without knowing how many there are or what they are called.)

The obvious would be:

myclass = MyClass() myclass['name'] = "My name" 

But that doesn't work.

Any ideas?

like image 498
Honza Pokorny Avatar asked Mar 11 '10 13:03

Honza Pokorny


People also ask

What is dynamic attribute in Python?

Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python.

What is __ Getattribute __ in Python?

__getattribute__This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.

How do you create a dynamic class 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.


1 Answers

setattr(my_class_instance, 'attr_name', attr_value) 
like image 182
shylent Avatar answered Sep 21 '22 19:09

shylent