Special Method and Class
Yermat
loic at yermat.net1.nerim.net
Thu Apr 8 14:07:01 EDT 2004
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__)
... def __str__(cls):
... return "<test %s>" % cls.__name__
... __str__ = classmethod(__str__)
...
>>> print Test
<class '__main__.Test'>
>>> print str(Test)
<class '__main__.Test'>
>>> print repr(Test)
<class '__main__.Test'>
>>> print Test.__repr__()
<special Test>
In fact, what I want to do is with __iter__ :
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
Yermat
More information about the Python-list
mailing list