Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to implement function overloading in Python:

class A:

    def fun1(self):    

        print 'first method'

    def fun1(self, i):

        print 'second method', i

ob=A()

ob.fun1(2)

but the result is second method 2; similarly:

class A:

    def fun(self):    

        print 'first method'

    def fun(self, i):

        print 'second method', i

ob=A()

ob.fun()

#gives

Traceback (most recent call last):

  File "my.py", line 9, in <module>

    ob.fun()

TypeError: fun() takes exactly 2 arguments (1 given)

How do I make this implement?

1 Answer

0 votes
by (108k points)

Please be informed that it is method overloading, not method overriding. And in Python, you can perform it all in one function:

class A:

    def fun(self, i='some_default_value'):

        print 'only method'

ob=A()

ob.fun(2)

ob.fun()

You can't have two functions with the same name in Python. Kick-start your career in Python with the Intellipaat's perfect Python Course now!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Mar 22, 2021 in Python by Rekha (2.2k points)
0 votes
1 answer

Browse Categories

...