【问题标题】:Method overloading with the same signature in python在python中具有相同签名的方法重载
【发布时间】:2015-11-18 07:28:19
【问题描述】:
class testClass(object):
    def test1(self):
        print "1"
    def test1(self):
        print "2"
    def test1(self):
        print "3"

这是一个包含三个方法的类,它们都具有相同的名称(甚至相同的签名)

当我这样称呼时:

tc = testClass()
tc.test1()

它没有抛出任何错误,而是简单地打印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"

如果我再次调用tc.test1(),它会引发异常:

TypeError: test1() takes exactly 4 arguments (1 given)

那么我可以假设在这些情况下它总是会执行类中定义的最后一个方法吗?

PS:我对文件中的各个函数进行了相同的尝试,得到了相同的结果,它执行了最后一个函数。

【问题讨论】:

  • Python 不是 Java。 Five-minute Multimethods in Python.
  • 你替换了一个录音函数,因此最后执行。对于未指定数量的参数,请阅读 *args 和 **kwargs

标签: python python-2.7 python-3.x overloading


【解决方案1】:

是的,当 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

作为最后一点,仅仅因为 Python 不为您提供固有的重载并不意味着您不能自己实现该功能。

经过一番搜索,我在 this repo 中找到了一个很好的例子,它公开了一个用于重载函数的 @overloaded@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'.

爱上 Python 社区。

【讨论】:

    【解决方案2】:

    那么我可以假设在这种情况下它总是会执行类中的最后一个方法吗?

    你没看错。您的第一个示例相当于:

    x = 1
    x = 2
    x = 3
    print x
    >> 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-23
      • 2019-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2012-04-29
      • 2015-06-09
      相关资源
      最近更新 更多