Can't define __call__ within __init__?

Peter Otten __peter__ at web.de
Thu Mar 11 11:36:03 EST 2010


Steve Howell wrote:

> On Mar 10, 7:18 pm, Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:

>> (2) special methods like __call__ are only called on the class, not the
>> instance, so you can't give each instance its own method.

> Are you sure about that?  This program prints 1, 2, 1, 2.
 
You are using a classic class while the behaviour described above applies to 
newstyle classes:

>>> class Foo:
...     def __init__(self):
...             self.__call__ = lambda: 42
...
>>> Foo()()
42
>>> class Bar(object):
...     def __init__(self):
...             self.__call__ = lambda: 42
...
>>> Bar()()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Bar' object is not callable

I don't think it's a good idea to write new code that requires a classic 
class.

Peter



More information about the Python-list mailing list