gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:26:31 24 4
gpt4 key购买 nike

我正在尝试在 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)

关于python - 如何在 Python 中使用方法重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10202938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com