harsh
harsh

Reputation: 97

How can I write a method that can be called with different numbers of parameters?

My code below:

class A:
    def TestMethod(self):
        print 'first method'

    def TestMethod(self, i):
        print 'second method', i

ob = A()
ob.TestMethod()
ob.TestMethod(10)

It give an error..

Traceback (most recent call last):
File "stack.py", line 9, in <module>
    ob.TestMethod()
TypeError: TestMethod() takes exactly 2 arguments (1 given)

How can I have a method that can be called with different numbers of parameters?

Upvotes: 1

Views: 96

Answers (2)

hspandher
hspandher

Reputation: 16733

If you just want to optionally pass one argument, then you can use poke's solution. if you really want to provide support for large number of optional arguments , then you should use args and kwargs.

class A:
    def TestMethod(self, *args):
        if not args:
            print 'first method'
        else:
            print 'second method', args[0]

Upvotes: 0

poke
poke

Reputation: 387637

Python does not support method overloading. That’s very common for dynamically typed languages since while methods are identified by their full signature (name, return type, parameter types) in statically typed languages, dynamically typed languages only go by name. So it just cannot work.

You can however put the functionality within the method by specifying a default parameter value which you then can check for to see if someone specified a value or not:

class A:
    def TestMethod(self, i = None):
        if i is None:
            print 'first method'
        else:
            print 'second method', i

Upvotes: 6

Related Questions