Quesion about the proper use of __slots__

bonono at gmail.com bonono at gmail.com
Mon Feb 20 03:45:21 EST 2006


Zefria wrote:
> >>> class Fighter:
> ...     '''Small one man craft that can only harm other fighters on
> their own.'''
> ...     def __init__(self,statsTuple=(50,5,0,(2,4),1)):
> ...             self.fuel = statsTuple[0]
> ...             self.life = statsTuple[1]
> ...             self.armor = statsTuple[2]
> ...             self.weapon = statsTuple[3]
> ...             self.bulk = statsTuple[4]
> ...             __slots__ =
> [self.fuel,self.life,self.armor,self.weapon,self.bulk]
> ...
> >>> ral = Fighter()
> >>> ral.rocks = 2
> >>> ral.rocks
> 2
> >>> ral.life
> 5
>
> I was reading the special methods, got to slots
> (http://docs.python.org/ref/slots.html) and decided that i should use
> this to save memory in the program because it'll have to support very
> large numbers of fighers at once. It says that once you define slots
> then you can't add any variables not listed in slots, but from that
> example section I just did, so am I doing something wrong or did I read
> it wrong?

Seems that __slots__  in your case is nothing but a 'local variable' to
the function __init__. I think you need something like this :

class Test(object):
  __slots__ = ['attr1','attr2']




More information about the Python-list mailing list