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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With