Can't define __call__ within __init__?

Duncan Booth duncan.booth at invalid.invalid
Wed Mar 10 12:39:27 EST 2010


Neal Becker <ndbecker2 at gmail.com> wrote:

> What I'm trying to do is make a callable whose behavior is switched
> based on some criteria that will be fixed for all calls.  In my
> example, this will ultimately be determined by the setting of a
> command line switch. 
> 
If you want different behaviour its usually best to use different classes.

You can keep all the common behaviour in a base class and just override the 
__call__ method for the different behaviour. Then use a factory function to 
decide which class to instantiate or else override __new__ and make the 
decision there. e.g.

>>> class X(object):
	def __call__(self):
		return 0
	def __new__(cls, i):
		if i!=0:
			cls = Y
		return object.__new__(cls)

	
>>> class Y(X):
	def __call__(self):
		return 1

	
>>> x = X(0)
>>> x()
0
>>> y = X(1)
>>> y()
1
>>> isinstance(x, X)
True
>>> isinstance(y, X)
True

P.S. I don't know what you did in your post but your Followup-To header is 
pointing to a group on gmane which makes extra work for me replying. Please 
don't do that.



More information about the Python-list mailing list