-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))
4
  • 1
    There is no such thing as method overloading in Python. Only the second version actually wins. Commented Sep 3, 2018 at 11:54
  • See the duplicate on how to define methods that can take a variable number of arguments. Commented Sep 3, 2018 at 11:55
  • @MartijnPieters Not sure why, but only the 5th answer in the dup (by upvotes) mentions star arguments. Commented Sep 3, 2018 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. Commented Sep 3, 2018 at 11:58

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.