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 write
a.f = 2
instead o开发者_StackOverflow中文版fa['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 Bunch
in the Python Cookbook, allowing you to do declaration and assignment in one:
point = Bunch(x=x, y=y, squared=y*y)
point.x
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.
No, you have to subclass object
to get a mutable object. Make sure to do so explicitly in python 2.x:
class Struct(object):
pass
Probably using a built-in container is better though, if only because it's clear from syntax exactly what it is.
The reason instances of object
can't be assigned to is that they don't have either a __dict__
or a __slots__
attribute, the two places where instance data can be stored.
>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Basically this is equivalent to declaring __slots__ = []
.
If you know all the fields you want your Struct
to have, you could use slots
to make a mutable namedtuple
-like data structure:
>>> class Foo(object):
... __slots__ = ['a', 'b', 'c']
...
>>> f = Foo()
>>> f.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: a
>>> f.a = 5
>>> f.a
5
But you can only assign values to attribute names listed in __slots__
:
>>> f.d = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'd'
Yes. Its called a dict.
structything = {}
structything['f'] = 2
print structything['f']
print structything.get('f')
Id link you to the documents but they are down atm.
精彩评论