roc*_*rty 5 python overloading python-2.7 python-3.x
class testClass(object):
def test1(self):
print "1"
def test1(self):
print "2"
def test1(self):
print "3"
Run Code Online (Sandbox Code Playgroud)
这是一个包含三个方法的类,这些方法都具有相同的名称(甚至相同的签名)
当我这样称呼时:
tc = testClass()
tc.test1()
Run Code Online (Sandbox Code Playgroud)
它不会抛出任何错误,而是简单打印3。
再举一个例子:
class testClass(object):
def test1(self, a, b):
print "1"
def test1(self, a):
print "2"
def test1(self, a, b, c):
print "3"
Run Code Online (Sandbox Code Playgroud)
如果我再次调用tc.test1(),它会引发异常:
TypeError: test1() takes exactly 4 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
那么我可以假设在这些情况下它将始终执行类中定义的最后一个方法吗?
PS:我对文件中的各个函数进行了相同的尝试,并得到了相同的结果,它执行了最后一个函数。
是的,当 Python 遇到类语句时,它会执行这些def语句,以便为随后的类命名空间 ( __dict__) 创建正确的名称绑定。
与运行解释器一样,重新定义的名称会失去其旧值;它被替换为该特定名称的最新分配。
python 中没有方法重载,因为我们有那些很好的关键字参数,允许我们根据需要进行“重载”调用:
class A:
def f(self, a, b=None, c=None, d=None):
print(a, b, c, d, sep=" | ")
a = A()
a.f(1)
# out : 1 | None | None | None
a.f(1, 2)
# out : 1 | 2 | None | None
a.f(1, 2, 3)
# out : 1 | 2 | 3 | None
a.f(1, 2, 3, 4)
# out : 1 | 2 | 3 | 4
Run Code Online (Sandbox Code Playgroud)
最后一点,Python 不提供固有的重载并不意味着您无法自己实现该功能。
经过一番搜索后,我在这个存储库中找到了一个很好的例子,它公开了一个用于重载函数的@overloadedand装饰器:@overloads(func)
from overloading import *
@overloaded
def f():
return 'no args'
@overloads(f)
def f(foo):
return 'one arg of any type'
@overloads(f)
def f(foo:int, bar:int):
return 'two ints'
>>> f()
'no args'
>>> f('hello')
'one arg of any type'
>>> f('hello', 42)
TypeError: Invalid type or number of arguments when calling 'f'.
Run Code Online (Sandbox Code Playgroud)
爱上 Python 社区。
| 归档时间: |
|
| 查看次数: |
1520 次 |
| 最近记录: |