简体   繁体   中英

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?

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM