我正在尝试在 Python 中实现方法重载:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow(2)
但输出是 second method 2
;相似地:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow()
给
Traceback (most recent call last):
File "my.py", line 9, in <module>
ob.stackoverflow()
TypeError: stackoverflow() takes exactly 2 arguments (1 given)
我如何使这项工作?
原文由 user1335578 发布,翻译遵循 CC BY-SA 4.0 许可协议
它是方法 _重载_,而不是方法 _覆盖_。在 Python 中,您历来在一个函数中完成所有工作:
请参阅 Python 教程的 默认参数值 部分。请参阅 “Least Astonishment”和 Mutable Default Argument 了解要避免的常见错误。
有关 Python 3.4 中添加的单一分派泛型函数的信息,请参阅 PEP 443 :