Iterate through slots

Jared Grubb jared.grubb at gmail.com
Tue Jan 15 13:35:52 EST 2008


How can I iterate through the slots of a class, including those it inherits
from parent classes?

class C(object):
  __slots__ = ['a']

class D(C):
  __slots__ = ['b']

>>> d = D()
>>> d.__slots__
['b']
>>> d.a = 1 # this works, so slots inherit properly
>>> d.b = 2
>>> d.c = 3 # this doesnt work, like we expect
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'D' object has no attribute 'c'

The reason I want to do this is that I want to have the following, and let
all the children inherit the parent's __init__:

class Parent(object):
   __slots__ = ['whatever']
   def __init__(self, context=None, **kw):
     if context is None: context=getContext()
     for slot in SLOTITERATORHERE:
       # Resolve the slot's value, even for those things not specifically
set in kw

class Child1(Parent):
   __slots__ = ['for_me_only']
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080115/91a44b5e/attachment.html>


More information about the Python-list mailing list