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

我正在尝试在 Python 中实现方法重载:

class A:
    def stackoverflow(self):    
        print 'first method'
    def stackoverflow(self, i):
        print 'second method', i

ob=A()
ob.stackoverflow(2)

但输出是第二种方法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)

我该如何进行这项工作?

最佳答案

这是方法重载,而不是方法覆盖。而在 Python 中,过去你可以在一个函数中完成所有操作:

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

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

见 Default Argument Values Python 教程的部分。见 "Least Astonishment" and the Mutable Default Argument 避免一个常见的错误。

见 PEP 443有关 Python 3.4 中添加的单调度泛型函数的信息:

>>> 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)

https://stackoverflow.com/questions/10202938/

相关文章:

linux - WGET 是否超时?

python - 如何中止 Python 脚本的执行?

python - 我如何告诉 matplotlib 我完成了一个情节?

linux - Bash 中的多线程

linux - 了解 Linux oom-killer 的日志

python - 如何为子图设置公共(public)轴标签

linux - grep 不作为正则表达式

python - 如何从生成器构建 numpy 数组?

python - 如何使用 Python 登录网页并检索 cookie 以供以后使用?

python - 删除字符串的第一个字符