反射:通过字符串的形式去模块,对象中找寻指定的函数(方法)并执行。
hasattr
class Person(object): def talk(self): print('skr')p = Person()print(hasattr(p, 'talk'))print(hasattr(p, 'say_hello'))# True# False
getattr
class Person(object): def talk(self): print('skr')p = Person()func = getattr(p, 'talk')print(func)func()#># skr
setattr
def say_hello(self): print('hello!')class Person(object): def talk(self): print('skr')p = Person()setattr(p, 'say_hello', say_hello)p.say_hello(p) # hello!
delattr
class Person(object): def talk(self): print('skr')p = Person()delattr(p, 'talk')p.talk()Traceback (most recent call last): File "oop.py", line 8, indelattr(p, 'talk')AttributeError: 'Person' object attribute 'talk' is read-only p = Person() setattr(p, 'hehe', 111) p.hehe delattr(p, 'hehe') p.hehe Traceback (most recent call last): File "oop.py", line 12, in p.hehe AttributeError: 'Person' object has no attribute 'hehe'