Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Python class where the attributes is defined dynamically

Sorry if this has been asked before. Is it possible to create class in Python dynamically where attributes is not defined in the __init__ method of the class.

For example with this class

class Person(object):
  def __init__(self):
    ...

I can dynamically put in the attributes during initialization like this:

person = Person(name='Joe')

and access it like this:

person.name
>>> Joe

Thank you

like image 968
Joshua Partogi Avatar asked Mar 01 '11 11:03

Joshua Partogi


People also ask

How do I 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.

What are dynamic attributes 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.

How do I add attributes to a class in Python?

Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.


1 Answers

The easiest way to do this is to assign the keyword argument dict to the __dict__ attribute of the class:

class Person(object):
    def __init__(self, **kw):
        self.__dict__ = kw
person = Person(name='Joe')
print person.name

prints

Joe

To add attributes after object creation, use

def add_attributes(self, **kw):
    self.__dict__.update(kw)

You could also use .update() in the constructor.

like image 89
Sven Marnach Avatar answered Oct 06 '22 00:10

Sven Marnach