我的代码如下:
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)
如何使用不同数量的参数调用方法?
答案 0 :(得分:6)
Python不支持方法重载。这对于动态类型语言来说非常常见,因为虽然方法是通过静态类型语言中的完整签名(名称,返回类型,参数类型)来标识的,但动态类型语言只能按名称进行。所以它无法运作。
但是,您可以通过指定默认参数值将该功能放在方法中,然后您可以检查该值是否有人指定了值:
class A:
def TestMethod(self, i = None):
if i is None:
print 'first method'
else:
print 'second method', i
答案 1 :(得分:0)
如果您只想选择传递一个参数,那么您可以使用poke的解决方案。如果你真的想为大量可选参数提供支持,那么你应该使用args和kwargs。
class A:
def TestMethod(self, *args):
if not args:
print 'first method'
else:
print 'second method', args[0]