反射:通过字符串的形式去模块,对象中找寻指定的函数(方法)并执行。
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() # <bound method Person.talk of <__main__.Person object at 0x0000000002A73358>> # 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, in <module> delattr(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 <module>
p.hehe
AttributeError: 'Person' object has no attribute 'hehe'