新聞中心
這篇文章主要為大家展示了“Python中反射的示例分析”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Python中反射的示例分析”這篇文章吧。
反射
在Python中,能夠通過(guò)一個(gè)對(duì)象,找出type、class、attribute或者method的能力,成為反射。
函數(shù)與方法
內(nèi)建函數(shù):
getattr(object,name[,degault]) 通過(guò)name返回object的屬性值,當(dāng)屬性不存在,將使用default返回,如果沒(méi)有default,則拋出AttributeError。Name必須為字符串。
setattr(object,name,value) object的屬性存在,則覆蓋,不存在,新增。
hasattr(object,name) 判斷對(duì)象是否有這個(gè)名字的屬性,name必須為字符串
介紹了基本知識(shí)點(diǎn),我們來(lái)看下實(shí)例代碼:
#!/usr/bin/env python #-*-coding:utf8-*- def bulk(self): print("%s is jiao ...."%self.name) class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("%s is eating ...."%self.name,food) d= Dog("dfxa") choice = input(">>:").strip() if hasattr(d,choice): #判斷一個(gè)d(對(duì)象)里是否有對(duì)應(yīng)的choice字符串方法 # delattr(d,choice) # Deletes the named attribute from the given object. # delattr(x, 'y') is equivalent to ``del x.y'' # 相當(dāng)于 del d.choice func = getattr(d,choice) #根據(jù)字符串去獲取d對(duì)象里的對(duì)應(yīng)方法的內(nèi)存地址 func("cheng") # attr = getattr(d,choice) # setattr(d,choice,"drr") else: # 將給定對(duì)象的命名屬性設(shè)置為指定值 setattr(d,choice,22) # choice是字符串,相當(dāng)于 d.choice = z print(getattr(d,choice)) print(d.name)
第二短代碼:
def bulk(self): print("%s is jiao ...."%self.name) class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("%s is eating ...."%self.name,food) d= Dog("dfxa") choice = input(">>:").strip() if hasattr(d,choice): #判斷一個(gè)d(對(duì)象)里是否有對(duì)應(yīng)的choice字符串方法 func = getattr(d,choice) #根據(jù)字符串去獲取d對(duì)象里的對(duì)應(yīng)方法的內(nèi)存地址 func("cheng") #不能直接print(d.choice) ,choice是一個(gè)字符串,應(yīng)該按照下面的方法寫(xiě) # attr = getattr(d,choice) # print(attr) else: setattr(d,choice,bulk) # 運(yùn)行程序,輸入talk相當(dāng)于 d.talk = bulk,把bulk的內(nèi)存地址賦給了talk # 此時(shí)函數(shù)就是talk,talk() == 調(diào)用bulk() #d.talk(d) #所以這里只能調(diào)用talk() #動(dòng)態(tài)的把類(lèi)外面的方法裝配到類(lèi)里,通過(guò)字符串的形式,但調(diào)用需要把自己(對(duì)象)傳進(jìn)去 #這樣的話就把函數(shù)寫(xiě)死了,另一種寫(xiě)法 func2 = getattr(d,choice) func2(d) #這樣不管輸入的是talk還是bulk都可以 >>:talk dfxa is jiao ....
以上是“Python中反射的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享題目:Python中反射的示例分析-創(chuàng)新互聯(lián)
鏈接地址:http://www.ef60e0e.cn/article/cedeoe.html