Joshua Partogi
Joshua Partogi

Reputation: 16435

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

Upvotes: 5

Views: 2151

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 602485

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.

Upvotes: 14

Björn Pollex
Björn Pollex

Reputation: 76866

This can be achieved by using descriptors (detailed explanation). This also enables you to add attributes after the object has been created.

Upvotes: 0

Related Questions