Reputation: 16435
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
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
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