繁体   English   中英

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

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

我的代码如下:

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

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

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

它给出一个错误..

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

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

Python不支持方法重载。 对于动态类型的语言,这是很常见的,因为虽然方法在静态类型的语言中由其完整签名(名称,返回类型,参数类型)标识,但是动态类型的语言仅按名称进行命名。 因此,它根本无法工作。

但是,您可以通过指定默认参数值将功能放入方法中,然后可以检查默认参数值以查看是否有人指定了值:

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

如果您只想选择传递一个参数,则可以使用poke的解决方案。 如果您确实想为大量可选参数提供支持,则应使用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