我的代码如下:
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
