Quesion about the proper use of __slots__
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Mon Feb 20 07:16:43 EST 2006
On Mon, 20 Feb 2006 01:14:20 -0800, Zefria wrote:
>>>> class Fighter(object):
> ... '''Small one man craft that can only harm other fighters on
> their own.'''
> ... __slots__ = ["fuel","life","armor","weapon","bulk"]
> ... 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]
> ...
>>>> examp = Fighter()
>>>> examp.rock = 3
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> AttributeError: 'Fighter' object has no attribute 'rock'
>>>>
>
> Thank you both, I had tried making it a class variable and didn't see
> anything. The trick must have been in making a class that inheriets
> from object.
For technical reasons, __slots__ don't work as expected for old-style
classes, and never will. You have to inherit from object to make them work
correctly.
> Also, I don't generally do any optimization at all yet (as a highschool
> student projects get trashed often enough no to bother over), but in
> this special case I'm expecting each "carrier" to have up to 150
> fighters, and 3 to 5 carriers for each of the two teams, which comes
> out to be quite large.
750 objects is not very many, not unless they are carrying around large
chunks of data. And even then, using __slots__ saves only a small
amount of memory per object.
Write your code the slot-less way, see how it performs, and if it is slow,
change your class definition.
--
Steven.
More information about the Python-list
mailing list