Special Method and Class
Jack Diederich
jack at performancedrivers.com
Thu Apr 8 14:47:49 EDT 2004
On Thu, Apr 08, 2004 at 08:07:01PM +0200, Yermat wrote:
> Hi all,
>
> Why does special methods not work on class ? Or how to make them work ?
> Here a simple example :
>
> >>> class Test(object):
> ... def __repr__(cls):
> ... return "<special %s>" % cls.__name__
> ... __repr__ = classmethod(__repr__)
> ...
> >>> print repr(Test)
> <class '__main__.Test'>
This is your clue, this didn't print <special Test>
for the same reason the __iter__ does work below.
The special __method__'s only work for instances of
the class and not for the class itself.
>>> print repr(Test)
<class '__main__.Test'>
>>> print repr(Test())
<special Test>
> import weakref
> class RememberInstance(object):
> instances = []
>
> def __init__(self,name):
> self.name = name
> self.__class__.instances.append(weakref.ref(self))
>
> def __iter__(cls):
> for wref in cls.instances:
> inst = wref()
> if inst:
> yield inst
> __iter__ = classmethod(__iter__)
>
>
> t1 = RememberInstance('t1')
> t2 = RememberInstance('t2')
>
> for inst in RememberInstance:
> print inst.name
>
drop the __iter__ altogether and just iterate over the class's list
for (inst) in RememberInstance.instances:
if (inst()): # the weakref hasn't expired
print inst().name
It is much clearer and less magic to boot.
-jackdied
More information about the Python-list
mailing list