简体   繁体   English

如何编写可以使用不同数量的参数调用的方法?

[英]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. Python不支持方法重载。 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. 如果您只想选择传递一个参数,则可以使用poke的解决方案。 if you really want to provide support for large number of optional arguments , then you should use args and kwargs. 如果您确实想为大量可选参数提供支持,则应使用args和kwargs。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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