I wish to make an instance of built-in class object, and use it as container for some variables (like struct in C++):
Python 3.2 (r32:88445, Mar 25 2011, 19:56:22)
>>> a=object()
>>> a.f=2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'f'
Is there a way to accomplish this easier than doing:
>>> class struct():
... '''Container'''
...
>>> a=struct()
>>> a.f=2
>>> a.f
2
>>>
UPDATE:
-
i need a container to hold some variables, but i don’t want to use
dict – to be able to writea.f = 2instead ofa['f'] = 2 -
using a derived class saves you from typing the quotes
-
also, sometimes autocomplete works
I recognize the sentiment against dicts, and I therefore often use either NamedTuples or classes. Nice short hand is provided by
Bunchin the Python Cookbook, allowing you to do declaration and assignment in one:The printed Cookbook (2ed) has an extensive discussion on this.
IMHO, the reason why object has no slots and no dict is readability: If you use an (anonymous) object to store coordinates first and then another object to store client data, you may get confused. Two class definitions makes it clear which one is which. Bunches don’t.