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

2024-04-20 14:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

ob=A()
ob.stackoverflow(2)

但是输出是second method 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)

我该怎么做?


Tags: 方法selfmostdefcallstackoverflowmethodclass
3条回答

也可以使用pythonlangutil

from pythonlangutil.overload import Overload, signature

class A:
    @Overload
    @signature()
    def stackoverflow(self):    
        print 'first method'

    @stackoverflow.overload
    @signature("int")
    def stackoverflow(self, i):
        print 'second method', i

这是方法重载而不是方法重写。在Python中,您可以在一个函数中完成这一切:

class A:

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

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

在Python中,不能有两个同名的方法,也不需要。

请参阅Python教程的Default Argument Values部分。请参阅"Least Astonishment" and the Mutable Default Argument以了解要避免的常见错误。

编辑:有关Python 3.4中新的单分派泛型函数的信息,请参见PEP 443

在Python中,你不会那样做。当人们在Java这样的语言中这样做时,他们通常需要一个默认值(如果不需要,他们通常需要一个具有不同名称的方法)。所以,在Python中,you can have default values

class A(object):  # Remember the ``object`` bit when working in Python 2.x

    def stackoverflow(self, i=None):
        if i is None:
            print 'first form'
        else:
            print 'second form'

如您所见,您可以使用这个来触发单独的行为,而不仅仅是有一个默认值。

>>> ob = A()
>>> ob.stackoverflow()
first form
>>> ob.stackoverflow(2)
second form

相关问题 更多 >