我试图在Python中实现方法重载:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow(2)
Run Code Online (Sandbox Code Playgroud)
但输出是second method 2; 类似的:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow()
Run Code Online (Sandbox Code Playgroud)
给
Traceback (most recent call last):
File "my.py", line 9, in <module>
ob.stackoverflow()
TypeError: stackoverflow() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
我该如何工作?
说我有一个这样定义的函数:
def inner_func(spam, eggs):
# code
Run Code Online (Sandbox Code Playgroud)
然后,我想调用这样的函数:
outer_func(spam=45, eggs="blah")
Run Code Online (Sandbox Code Playgroud)
在内部,outer_func我希望能够inner_func使用与传入的参数完全相同的参数进行调用outer_func。
可以这样编写outer_func:
def outer_func(spam, eggs):
inner_func(spam, eggs)
Run Code Online (Sandbox Code Playgroud)
但是,我希望能够更改参数inner_func接受,并相应地更改传递给我的参数outer_func,而不必outer_func每次都更改任何内容。
有(简便)方法可以做到这一点吗?请使用Python 3。