鍑芥暟閲嶈浇涓昏鏄负浜嗚В鍐充袱涓棶棰樸€?/p>
- 鍙彉鍙傛暟绫诲瀷銆?/li>
- 鍙彉鍙傛暟涓暟銆?/li>
鍙﹀锛屼竴涓熀鏈殑璁捐鍘熷垯鏄紝浠呬粎褰撲袱涓嚱鏁伴櫎浜嗗弬鏁扮被鍨嬪拰鍙傛暟涓暟涓嶅悓浠ュ锛屽叾鍔熻兘鏄畬鍏ㄧ浉鍚岀殑锛屾鏃舵墠浣跨敤鍑芥暟閲嶈浇锛屽鏋滀袱涓嚱鏁扮殑鍔熻兘鍏跺疄涓嶅悓锛岄偅涔堜笉搴斿綋浣跨敤閲嶈浇锛岃€屽簲褰撲娇鐢ㄤ竴涓悕瀛椾笉鍚岀殑鍑芥暟銆?/p>
濂藉惂锛岄偅涔堝浜庢儏鍐?1 锛屽嚱鏁板姛鑳界浉鍚岋紝浣嗘槸鍙傛暟绫诲瀷涓嶅悓锛宲ython 濡備綍澶勭悊锛熺瓟妗堟槸鏍规湰涓嶉渶瑕佸鐞嗭紝鍥犱负 python 鍙互鎺ュ彈浠讳綍绫诲瀷鐨勫弬鏁帮紝濡傛灉鍑芥暟鐨勫姛鑳界浉鍚岋紝閭d箞涓嶅悓鐨勫弬鏁扮被鍨嬪湪 python 涓緢鍙兘鏄浉鍚岀殑浠g爜锛屾病鏈夊繀瑕佸仛鎴愪袱涓笉鍚屽嚱鏁般€?/p>
閭d箞瀵逛簬鎯呭喌 2 锛屽嚱鏁板姛鑳界浉鍚岋紝浣嗗弬鏁颁釜鏁颁笉鍚岋紝python 濡備綍澶勭悊锛熷ぇ瀹剁煡閬擄紝绛旀灏辨槸缂虹渷鍙傛暟銆傚閭d簺缂哄皯鐨勫弬鏁拌瀹氫负缂虹渷鍙傛暟鍗冲彲瑙e喅闂銆傚洜涓轰綘鍋囪鍑芥暟鍔熻兘鐩稿悓锛岄偅涔堥偅浜涚己灏戠殑鍙傛暟缁堝綊鏄渶瑕佺敤鐨勩€?/p>
濂戒簡锛岄壌浜庢儏鍐?1 璺?鎯呭喌 2 閮芥湁浜嗚В鍐虫柟妗堬紝python 鑷劧灏变笉闇€瑕佸嚱鏁伴噸杞戒簡銆?/p>
I鈥榤 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鈥榤 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鈥榤 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