python方法调用名字不一样,如何在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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值