反射是什么,what why how

反射也叫内省,就是让对象自己告诉我们它都有什么方法

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'

猜你喜欢

转载自blog.51cto.com/13118411/2120060