1. 程式人生 > >python中反射的三個方法hasattr,getattr,setattr

python中反射的三個方法hasattr,getattr,setattr

python

hasattr(obj,attr) getattr(obj,attr) setattr(obj,attr,val)
class People:
    def eat(self):
        print(‘eat‘)
    def drink(self):
        print(‘drink‘)
    def code(self):
        print(‘code‘)
p = People()   # p為指向類的實例
hasattr(p,‘eat‘)  # 在實例中是否有eat方法  
True
hasattr(p,‘code‘) 
True
getattr(p,‘code‘)  # 在實例中取code方法
<bound method People.code of <__main__.People object at 0x000001A5E387E4E0>>
code123 = getattr(p,‘code‘)
code123()      # 調用類的的方法
code
setattr(p,‘sleep‘,‘sleep1234‘)  # 在實例中設置sleep屬性值為"sleep1234"
p.sleep            # 調用實例內sleep方法
‘sleep1234‘

python中反射的三個方法hasattr,getattr,setattr