Implementing class attribute access methods via pseudo-function o verloading.

Duncan Booth duncan.booth at invalid.invalid
Mon Oct 25 07:31:07 EDT 2004


Doran_Dermot at emc.com wrote:

> Am I correct in stating that Python does not support function
> overloading? Have I been hiding under a rock and not noticed the
> thousands of examples that illustrate this approach?
> 

Have you considered writing your example this way:

class Problems:
  def __init__( self, refNum ):
    self._refNum = refNum
    self.Title = ""
    self.Problem = ""

Now you can write your code as:

theProblem = Problems( "12345" )

print "Title: ", theProblem.Title
print "Problem: ", theProblem.Problem

theProblem.Title = "Java affecting adoption of Python."
theProblem.Problem = '''Developers are more inclined to use Java instead of
Python due to the fact that Java is seen as a defacto standard.'''

This is much clearer than wrapping your attributes up in accessor and 
mutator functions and doesn't lose you *anything*. If your code ever 
evolves to the point where you need to intercept the attribute access or 
mutation then you simply change the affected attributes into properties, 
but there is no need to make them properties until this happens.

Python does support function overloading (if you care to write a library 
that implements it), but in general it isn't needed. Some languages use 
overloading primarily as a means of specifying default arguments (in fact 
that is all you did in your example) and Python already has default 
arguments. Alternatively you might use overloading to allow different types 
to be passed to a function, but Python will already let you do this. If the 
function implementations are significantly different then it may mean that 
overloading isn't appropriate anyway. If the function implementations are 
largely the same then you may be able to share the definition in Python, 
possibly with a line or two to sort out the argument types.

It can often be clearer to use different names for functions instead of 
overloading them as the names can be used to hint at the type of argument 
expected. Doing it this way also means that you can 'overload' on semantics 
rather than just the type.

For example consider the function buildFrobozz(x) which I want to overload 
to accept either a string or a filename. Oops! I can't use overloaded 
functions for that, I have to call my methods buildFrobozzFromString(s) and 
buildFrobozzFromFilename(fname). Now I add another function that builds a 
frobozz from an open file. Calling it buildFrobozzFromFile(f) doesn't seem 
to me to be losing anything.

(Actually, I would probably make all of those class methods of the Frobozz 
class and call them fromString, fromFilename, fromFile for a bit more 
brevity.)




More information about the Python-list mailing list