How best to return a class method?

R

Roy Smith

I've got a method which returns another method:

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

I originally wrote it as the commented-out version, but didn't like
the idea that I've got to repeat the class name. The version using
self.__class__ solves that problem, but it's uglier and more
complicated.

Any opinions on the best way to do this?
 
S

Steven Bethard

Roy Smith said:
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:
.... @classmethod
.... def f(cls):
.... pass
....
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.
.... @classmethod
.... def f(cls):
.... print "C"
.... def c1(self):
.... return self.__class__.f
.... def c2(self):
.... return C.f
........ @classmethod
.... def f(cls):
.... print "D"
....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
 
B

Bruno Desthuilliers

Roy said:
I've got a method which returns another method:

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

I originally wrote it as the commented-out version, but didn't like
the idea that I've got to repeat the class name. The version using
self.__class__ solves that problem, but it's uglier and more
complicated.

Any opinions on the best way to do this?

I don't really notice anything uglier or more complicated here (2nd
solution), and that's how I'd do it, unless I have some compelling
reason to prevent use of a redifined version of printUnknown in a child
class (for now, I never found a compelling enough reason...)

Bruno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top