staticmethod and __call__
Roeland Rengelink
r.b.rigilink at chello.nl
Wed Dec 12 04:51:05 EST 2001
Bruce Eckel wrote:
>
> Actually, I can simplify this in one sentence: if you can make
> __call__ a static method, then how do you create objects of that
> class?
>
When I first investigated this, I hoped something like this would work:
>>> class A(object):
... def __call__(*args, **kwargs):
... print 'called'
... return object.__new__(A, *args, **kwargs)
... __call__ = staticmethod(__call__)
And it does, in the sense that A.__call__() returns a new instance
>>> b = A.__call__()
called
>>> b
<__main__.A object at 0x8161574>
but, A() doesn't do A.__call__
>>> A()
<__main__.A object at 0x815ed7c>
That is, implementing __call__ such that is does return (new) instances
is no problem. However, you can't convince Python to translate A() in
A.__call__(). I used to think this was to bad, but now think is actually
a good thing
By the way, having remembered __new__, here's your ItemGenerator again
>>> class ItemGenerator(object):
... rgen = random.Random()
... items = ['A', 'B', 'C']
... def __new__(cls): # __new__ is always a classmethod
... return cls.rgen.choice(cls.items)
...
>>> items = [ItemGenerator() for i in range(5)]
>>> items
['C', 'C', 'A', 'A', 'A']
Looking forward to your paper,
Roeland
--
r.b.rigilink at chello.nl
"Half of what I say is nonsense. Unfortunately I don't know which half"
More information about the Python-list
mailing list