如何在 Python 中使用方法重载?

新手上路,请多包涵

我正在尝试在 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 许可协议

阅读 226
1 个回答

它是方法 _重载_,而不是方法 _覆盖_。在 Python 中,您历来在一个函数中完成所有工作:

 class A:
    def stackoverflow(self, i='some_default_value'):
        print('only method')

ob=A()
ob.stackoverflow(2)
ob.stackoverflow()

请参阅 Python 教程的 默认参数值 部分。请参阅 “Least Astonishment”和 Mutable Default Argument 了解要避免的常见错误。

有关 Python 3.4 中添加的单一分派泛型函数的信息,请参阅 PEP 443

 >>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)
>>> @fun.register(int)
... def _(arg, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @fun.register(list)
... def _(arg, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)

原文由 agf 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏