instance introspection and __slots__
David Mertz, Ph.D.
mertz at gnosis.cx
Wed Oct 16 00:32:29 EDT 2002
|def attr_dict(o, fillslots=0):
| if hasattr(o,'__dict__'): [...]
| elif hasattr(o,'__slots__'): [...]
| else:
| raise TypeError, "Object has neither __dict__ nor __slots__"
"Delaney, Timothy" <tdelaney at avaya.com> wrote previously:
|You may want to add the case where an object has both __dict__ and
|__slots__.
I'm probably just being daft here... but would you show me an object
that has both __dict__ and __slots__? I kinda thought the one excluded
the other (but I'm probably not accounting for some inheritence case or
something). E.g.
>>> class Slotty(object):
... __slots__ = ('foo','bar')
... def __init__(self):
... self.foo = 1
... self.bar = 2
...
>>> slotty = Slotty()
>>> slotty.__slots__
('foo', 'bar')
>>> slotty.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Slotty' object has no attribute '__dict__'
>>> slotty.other = 3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Slotty' object has no attribute 'other'
>>> class NoSlot(object):
... def __init__(self):
... self.foo = 1
... self.bar = 2
...
>>> noslot = NoSlot()
>>> noslot.__slots__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'NoSlot' object has no attribute '__slots__'
>>> noslot.__dict__
{'foo': 1, 'bar': 2}
>>> noslot.other = 3
>>> noslot.__dict__
{'foo': 1, 'bar': 2, 'other': 3}
Yours, David...
--
mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i
gnosis _/_/ Postmodern Enterprises _/_/ s r
.cx _/_/ MAKERS OF CHAOS.... _/_/ i u
_/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s
More information about the Python-list
mailing list