using an instance of Object as an empty class
steve+comp.lang.python at pearwood.info
steve+comp.lang.python at pearwood.info
Wed Jun 29 13:07:17 EDT 2011
Ulrich Eckhardt wrote:
> Peter Otten wrote:
>> Examples for classes that don't accept attributes are builtins
>> like int, tuple, and -- obviously -- dict. You can make your own
>> using the __slot__ mechanism:
>>
>>>>> class A(object):
>> ... __slots__ = ["x", "y"]
>> ...
>>>>> a = A()
>>>>> a.x = 42
>>>>> a.y = "yadda"
>>>>> a.z = 123
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> AttributeError: 'A' object has no attribute 'z'
>
> Wow. This is something I've been missing dearly in my toolbox until now!
> Typically, when in C++ I would have used a struct, I always created a
> class that set the according attributes in the init function instead,
> which is quite a bit more cumbersome. Or I used a tuple and hoped to get
> the position of the elements correct.
Often, the right solution for that is to use collections.namedtuple:
>>> from collections import namedtuple as nt
>>> struct = nt('struct', 'x y z spam ham cheese')
>>> obj = struct(x=2, spam='tasty', y=3, z=0, cheese=None, ham='')
>>> obj
struct(x=2, y=3, z=0, spam='tasty', ham='', cheese=None)
namedtuple is available starting in Python 2.6.
This is not quite a struct, because it is immutable like all tuples. So
while you can access fields either by position or name:
>>> obj[1]
3
>>> obj.y
3
you can't modify them. This is usually a feature.
__slots__ are generally considered the wrong solution. They were added to
the language purely as an optimization for cases where you need huge
numbers of objects and the space required by all the instance.__dict__ was
prohibitive. Unfortunately, __slots__ don't play well with various other
aspects of Python (e.g. inheritance), see Christian's earlier post for more
details. But if you can live with the limits of __slots__, perhaps it will
work for you.
--
Steven
More information about the Python-list
mailing list