I would like to create an object then add attributes to the object on the fly. Here's some pseudocode EX1:
a = object()
a.attr1 = 123
a.attr2 = '123'
a.attr3 = [1,2,3]
EX2: the first page of this PDF
In Python is it possible to add attributes to an object on the fly (similar to the two examples I gave)? If yes, how?
If you are using Python 3.3+, use types.SimpleNamespace:
>>> import types
>>> a = types.SimpleNamespace()
>>> a.attr1 = 123
>>> a.attr2 = '123'
>>> a.attr3 = [1,2,3]
>>> a.attr1
123
>>> a.attr2
'123'
>>> a.attr3
[1, 2, 3]
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