函数重载主要是为了解决两个问题。
- 可变参数类型。
- 可变参数个数。
另外,一个基本的设计原则是,仅仅当两个函数除了参数类型和参数个数不同以外,其功能是完全相同的,此时才使用函数重载,如果两个函数的功能其实不同,那么不应当使用重载,而应当使用一个名字不同的函数。
好吧,那么对于情况 1 ,函数功能相同,但是参数类型不同,python 如何处理?答案是根本不需要处理,因为 python 可以接受任何类型的参数,如果函数的功能相同,那么不同的参数类型在 python 中很可能是相同的代码,没有必要做成两个不同函数。
那么对于情况 2 ,函数功能相同,但参数个数不同,python 如何处理?大家知道,答案就是缺省参数。对那些缺少的参数设定为缺省参数即可解决问题。因为你假设函数功能相同,那么那些缺少的参数终归是需要用的。
好了,鉴于情况 1 跟 情况 2 都有了解决方案,python 自然就不需要函数重载了。
I‘m learning Python (3.x) from a Java background.
I have a python program where I create a personObject and add it to a list.
p = Person("John")
list.addPerson(p)
But for flexibility I also want to be able to declare it directly in the addPerson method, like so:
list.addPerson("John")
The addPerson method will be able to differentiate whether or not I‘m sending a Person-object or a String.
In Java I would create two separate methods, like this:
void addPerson(Person p) {
    //Add person to list
}
void addPerson(String personName) {
    //Create Person object
    //Add person to list
}
I‘m not able to find out how to do this in Python. I know of a type() function, which I could use to check whether or not the parameter is a String or an Object. However, that seems messy to me. Is there another way of doing it?
EDIT:
I guess the alternative workaround would be something like this(python):
def addPerson(self, person):
    //check if person is string
        //Create person object
    //Check that person is a Person instance
        //Do nothing
    //Add person to list
But it seems messy compared to the overloading solution in Java.
Using the reference pointed by @Kevin you can do something like:
from multimethod import multimethod
class Person(object):
    def __init__(self, myname):
        self.name = myname
    def __str__(self):
        return self.name
    def __repr__(self):
        return self.__str__()
@multimethod(list, object)
def addPerson(l, p):
    l = l +[p]
    return l
@multimethod(list, str)
def addPerson(l, name):
    p = Person(name)
    l = l +[p]
    return l
alist = []
alist = addPerson(alist, Person("foo"))
alist = addPerson(alist, "bar")
print(alist)
The result will be:
$ python test.py [foo, bar]
(you need to install multimethod first)
http://www.it1352.com/779685.html
 
        