2021/06/05 — Edit:
I wrote this article last year, and since have learned more about how python works internally. The solution below indeed works, but is rather inefficient.
The getattr, setattr, hasattr, functions are great and have a time and place to be used, but they require a lookup of that object before accessing/checking for an attribute.
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.
class Example:
def __init__(self):
attr1 = 10 #Add an attribute upon initializationexample = Example()
example.attr2 = 12 #Add an attribute after initialization
But what if you don’t know what the attributes name is suppose to be? For an object it’s as simple as obj[‘NAME OF ATTR’] = value, but for a class you cannot index with brackets. You will get an object is not subscriptable error.
The Solution
Adding an attribute dynamically to a class is as simple as using the setattr function. See below:
#Example class
class Example:
def __init__(self):
attr1 = 10#Instance of class…