How best to return a class method?

Steven Bethard steven.bethard at gmail.com
Thu Oct 7 14:16:28 EDT 2004


Roy Smith <roy <at> panix.com> writes:

> class domPrinter:
>     def getNodePrinter (self, nodeType):
> 	[...]
>       # return domPrinter.printUnknown
> 	return self.__class__.printUnknown

I normally feel pretty comfortable with using the class name here.  It's the 
same idea as:

>>> class C(object):
...     @classmethod
...     def f(cls):
...             pass
...
>>> C.f()

Outside the class, I freely use the class name, so inside shouldn't be too 
different.

However, these two solutions don't have exactly the same behavior because the 
__class__ attribute of an object can be set.

>>> class C(object):
...     @classmethod
...     def f(cls):
...             print "C"
...     def c1(self):
...             return self.__class__.f
...     def c2(self):
...             return C.f
...
>>> class D(C):
...     @classmethod
...     def f(cls):
...             print "D"
...
>>> c = C()
>>> c.c1()()
C
>>> c.c2()()
C
>>> c.__class__ = D
>>> c.c1()()
D
>>> c.c2()()
C

So which version you want to use depends on the behavior you want.  Do you 
always want the printUnknown of domPrinter?  If so, use 
domPrinter.printUnknown.  If you want the printUnknown for the class of the 
self parameter, use self.__class__.printUnknown


Steve




More information about the Python-list mailing list