Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add attributes to an object dynamically?

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?

like image 229
Trevor Boyd Smith Avatar asked Aug 14 '13 14:08

Trevor Boyd Smith


1 Answers

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]
like image 181
falsetru Avatar answered Oct 08 '22 13:10

falsetru