Reputation: 10741
What I want to do in my code:
myobj = <SomeBuiltinClass>()
myobj.randomattr = 1
print myobj.randomattr
...
I can implement a custom SomeClass that implements __setattr__
__getattr__
.
But I wonder if there is already a built-in Python class or simple way to do this?
Upvotes: 4
Views: 832
Reputation: 4911
One solution is to use mock's:
from mock import Mock
myobj = Mock()
myobj.randomattr = 1
print myobj.randomattr
Second solution is to use namedtuple:
from collections import namedtuple
myobj = namedtuple('MyObject', '')
myobj.randomattr = 1
print myobj.randomattr
Upvotes: 0
Reputation: 10967
I like using the Bunch idiom for this. There are list of variations and some discussion here.
Upvotes: 2
Reputation: 27315
You can just use an empty class:
class A(object): pass
a = A()
a.randomattr = 1
Upvotes: 8