-3

I tried to add numpy arrays in method overloading but got error like TypeError: add() missing 1 required positional argument: 'n3'

import numpy as np
class addition:
    def add(self,n1,n2):
        return n1+n2
    def add(self,n1,n2,n3):
        return n1+n2+n3
s=np.array([[1,2,3],[3,4,4]])
s1=np.array([[1.0,2,3],[3,4,4]])
s3=np.array([[1.0,2.4,3.7],[3,4,4]])
c=addition()
print(c.add(1,2))
  • 1
    There is no such thing as method overloading in Python. Only the second version actually wins. – Martijn Pieters Sep 03 '18 at 11:54
  • See the duplicate on how to define methods that can take a variable number of arguments. – Martijn Pieters Sep 03 '18 at 11:55
  • @MartijnPieters Not sure why, but only the 5th answer in the dup (by upvotes) mentions star arguments. – DeepSpace Sep 03 '18 at 11:57
  • @DeepSpace: that's just one way of accepting a variable number of arguments. `*args` is only useful if you want to accept *any number of arguments*, from 0 to `sys.maxsize`. It's not always the right choice. – Martijn Pieters Sep 03 '18 at 11:58

1 Answers1

0

Python does not support overloading. The actual method will be the one that was defined the latest, as the error you get suggests.

Instead, use *args:

def add(self, *args):
    return sum(args)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154