python類的反射使用方法


曾經,博主的房東養了只金毛叫奶茶,今天就拿它當議題好了。

博主寫本文時正在被廣州的蚊子圍攻。

#反射練習

class animal(object):
    def __init__(self,name,fool):
        self.name = name
        self.fool = fool
    def dog(self):
        print("This is %s,it's a dog.it eat %s"%(self.name,self.fool))


d = animal("奶茶","meat")
anml_name = "dog"

#getattr(),用於判斷類中是否包含有某方法,如果有相應的方法則會返回類方法的內存地址,加()調用類方法
if getattr(d,anml_name):
    c = getattr(d,anml_name)
    c()
#hasattr()用於判斷類中是否包含某方法,如果有這個方法就返回True,沒有則返回False
print(hasattr(d,anml_name))
print(hasattr(d,"abc"))

#setattr設置屬性值,屬性必須存在
setattr(d,'name',"simb")
print("奶茶改名叫:%s"%d.name)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM