1. 程式人生 > >反射是什麽,what why how

反射是什麽,what why how

python

反射也叫內省,就是讓對象自己告訴我們它都有什麽方法

https://docs.python.org/3/library/functions.html?hight=hasattr#hasattr

1.hasattr(obj, attr): 這個方法用於檢查obj(對象)是否有一個名為attr的值的屬性,放回一個bool值

2.getattr(obj, attr): 調用這個方法將返回obj中名為attr值得屬性的值

3.setattr(obj, attr, val): 調用這個方法將給obj的名為attr的值的屬性賦值為val

s = ‘coop‘
s.upper()
‘COOP‘
isinstance(s,str)  # 檢查實例
True
hasattr(s,‘upper‘)  # 檢查字符串是否有這個屬性
True
class People:
    def eat(self):
        print(‘eat apple‘)

    def drink(self):
        print(‘drink water‘)

    def code(self):
        print(‘code python‘)

p = People()
p.eat()
eat apple
p.eat
<bound method People.eat of <__main__.People object at 0x000001AFCD677E80>>
hasattr(p,‘eat‘)
True
hasattr(p,‘code‘)
True
getattr(p,‘code‘)
<bound method People.code of <__main__.People object at 0x000001AFCD677E80>>
code123 = getattr(p,‘code‘)
print(code123)
<bound method People.code of <__main__.People object at 0x000001AFCD677E80>>
code123()
code python
setattr(p,‘sleep‘,‘sleeper‘)
p.sleep
‘sleeper‘

反射是什麽,what why how