反射--hasattr
class Person(object): def __init__(self, name, age): self.name = name self.age = age def qqxing(self): print('QQ星') alex = Person('alex', 36) # ret = getattr(alex, 'name') # 得到对象alex中实例变量name的值 # print(ret) # # ret = getattr(alex, 'qqxing') # 得到对象alex中qqxing函数的地址 # ret() # 调用qqxing函数 if hasattr(alex, 'name'): # 判断对象alex是否有name变量 ret = getattr(alex, 'name') print(ret) if hasattr(alex, 'qqxing'): if callable(getattr(alex, 'qqxing')): # 判断该函数地址是否可调用 getattr(alex, 'qqxing')()