Method overload in python

I need to call the non-parameterized method first , but also parameterize first , but it gives an error.

 >>> class A: ... def first(self): ... print 'first method' ... def first(self,f): ... print 'first met',f ... >>> a=A() >>> a.first() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: first() takes exactly 2 arguments (1 given) 

Is it possible to overload a method in Python, like in Java?

+6
python
Mar 15 2018-12-18T00:
source share
6 answers

The second method first overrides the original method first . In Python, it is not possible to create overloaded methods in the same way as in Java.

However, you can create methods with optional arguments and / or keywords and process them accordingly. Here is an example:

 class A: def first(self, f=None): if f is not None: print 'first met', f else: print 'first method' 

Using:

 a = A() a.first() a.first('something') 
+10
Mar 15 '12 at 18:38
source share

Python does not overload functions. This is due to the fact that it is a freely typed language. Instead, you can specify an unknown number of arguments and process their interpretation in function logic.

There are several ways to do this. You can specify specific optional arguments:

 def func1(arg1, arg2=None): if arg2 != None: print "%s %s" % (arg1, arg2) else: print "%s" % (arg1) 

By causing this, we get:

 >>> func1(1, 2) 1 2 

Or you can specify an unknown number of unnamed arguments (i.e., arguments passed in an array):

 def func2(arg1, *args): if args: for item in args: print item else: print arg1 

By causing this, we get:

 >>> func2(1, 2, 3, 4, 5) 2 3 4 5 

Or you can specify an unknown number of named arguments (i.e. the arguments passed in the dictionary):

 def func3(arg1, **args): if args: for k, v in args.items(): print "%s %s" % (k, v) else: print arg1 

By causing this, we get:

 >>> func3(1, arg2=2, arg3=3) arg2 2 arg3 3 

You can use these constructs to create the behavior you were looking for when overloaded.

+5
Mar 15 '12 at 18:52
source share

Usually you can define only one method in a class with a given name. In your example, the first method of argument 2 () argued for the first argument of first (). If you want to use two methods with the same name, in python 3 you should use functools.singledispatch and map the instance method name to your static method dispatcher, Ouch!

However, I really like implicit dynamic dispatch in OO programming, and I find it cleaner than writing manual dispatch logic in some kind of "master" first () function, which is repeated and fragile for expansion.

Asked question: add another method, for example A.first (A arg).

You will probably learn a lot about a system like python if you try to do this!

 #!/opt/local/bin/python3.4 from functools import singledispatch; class A(object): # default method handles dispatch for undefined types # note reversed positional args to match single dispatch functools @singledispatch def _first(arg, self): raise TypeError("no match for A._first(%s)" % type(arg)); # adapter maps instance call to (reversed) static method call def first(self, arg = None): return A._first(arg, self); # def first() @_first.register(type(None)) def _(none, self): print("A.first() called"); # def first(float f) @_first.register(float) def _(f, self): print("A.first(float %s) called" % f); a = A(); a.first(); # A.first() called a.first(None); # A.first() called a.first(3.14); # A.first(float 3.14) called class B(object): pass; b = B(); try: a.first(b); # no match for A._first(<class '__main__.B'>) except TypeError as ex: print(ex); 
+3
Jun 28 '15 at 16:44
source share

Check this code if it is useful:

 from math import pi class Geometry: def area(self,length = None,breadth = None,side = None,radius = None): self.length = length self.breadth = breadth self.side = side self.radius = radius if length != None and breadth != None: return length * breadth elif side != None: return side * side else: return pi * radius * radius obj1 = Geometry() print('Area of rectangle is {0}.'.format(obj1.area(length=5,breadth=4))) print('Area of square is {0}.'.format(obj1.area(side=5))) print('Area of circle is {0:.6}.'.format(obj1.area(radius=10))) 
+1
Dec 24 '16 at 6:35
source share

Python is not C ++ or Java; you cannot overload methods in the same way.

Indeed, the only way to do what you want is to check for the presence or absence of a second parameter:

 class A: def first(self, f=None): if f is None: print 'first method' else: print 'first met',f 

You can be even more complex and check the type f , but it can be dangerous and not always "pythonic". (However, it should be mentioned that one option for using function annotations in Python 3 is to allow such "general programming".)

0
Mar 15 '12 at 18:40
source share

While it is possible to create a system that seems to use overloaded methods, it is a little involved and usually not needed.

A regular idiom should have optional default parameters of None , for example:

 class A: def first(self, f=None): if f is None: print 'first method' else: print 'first met',f 

In your case, when you need other behavior based on whether this is the first call to this method, this is what I would do:

 class A: def first(self): print 'first method' self.first = self._first def _first(self, f): # '_' is convention for private name print 'first met',f 

and samples:

 a = A() a.first() a.first(3) 

prints:

 first method first met 3 
0
Mar 15 2018-12-18T00:
source share



All Articles