Python關(guān)于反射的實例代碼分享
反射
在Python中,能夠通過一個對象,找出type、class、attribute或者method的能力,成為反射。
函數(shù)與方法
內(nèi)建函數(shù):
getattr(object,name[,degault]) 通過name返回object的屬性值,當屬性不存在,將使用default返回,如果沒有default,則拋出AttributeError。Name必須為字符串。
setattr(object,name,value) object的屬性存在,則覆蓋,不存在,新增。
hasattr(object,name) 判斷對象是否有這個名字的屬性,name必須為字符串
介紹了基本知識點,我們來看下實例代碼:
#!/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): #判斷一個d(對象)里是否有對應(yīng)的choice字符串方法
# delattr(d,choice) # Deletes the named attribute from the given object.
# delattr(x, 'y') is equivalent to ``del x.y''
# 相當于 del d.choice
func = getattr(d,choice) #根據(jù)字符串去獲取d對象里的對應(yīng)方法的內(nèi)存地址
func("cheng")
# attr = getattr(d,choice)
# setattr(d,choice,"drr")
else:
# 將給定對象的命名屬性設(shè)置為指定值
setattr(d,choice,22) # choice是字符串,相當于 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): #判斷一個d(對象)里是否有對應(yīng)的choice字符串方法
func = getattr(d,choice) #根據(jù)字符串去獲取d對象里的對應(yīng)方法的內(nèi)存地址
func("cheng")
#不能直接print(d.choice) ,choice是一個字符串,應(yīng)該按照下面的方法寫
# attr = getattr(d,choice)
# print(attr)
else:
setattr(d,choice,bulk)
# 運行程序,輸入talk相當于 d.talk = bulk,把bulk的內(nèi)存地址賦給了talk
# 此時函數(shù)就是talk,talk() == 調(diào)用bulk()
#d.talk(d) #所以這里只能調(diào)用talk()
#動態(tài)的把類外面的方法裝配到類里,通過字符串的形式,但調(diào)用需要把自己(對象)傳進去
#這樣的話就把函數(shù)寫死了,另一種寫法
func2 = getattr(d,choice)
func2(d) #這樣不管輸入的是talk還是bulk都可以
>>:talk
dfxa is jiao ....
到此這篇關(guān)于Python關(guān)于反射的實例代碼分享的文章就介紹到這了,更多相關(guān)Python學習之反射內(nèi)容請搜素腳本之家以前的文章或下面相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章
python3獲取控制臺輸入的數(shù)據(jù)的具體實例
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于python3獲取控制臺輸入的數(shù)據(jù)的具體實例內(nèi)容,需要的朋友們可以學習下。2020-08-08
詳解Python設(shè)計模式編程中觀察者模式與策略模式的運用
這篇文章主要介紹了Python設(shè)計模式編程中觀察者模式與策略模式的運用,觀察者模式和策略模式都可以歸類為結(jié)構(gòu)型的設(shè)計模式,需要的朋友可以參考下2016-03-03
Pygame游戲開發(fā)之太空射擊實戰(zhàn)精靈的使用上篇
相信大多數(shù)8090后都玩過太空射擊游戲,在過去游戲不多的年代太空射擊自然屬于經(jīng)典好玩的一款了,今天我們來自己動手實現(xiàn)它,在編寫學習中回顧過往展望未來,下面開始講解精靈的使用2022-08-08

