Python反射
通过字符串映射或修改程序时的状态、属性、方法,有以下四种方法:
- getattr()
- hasattr()
- setattr()
- delattr()
hasattr(object,name)
判断一个对象里是否存在对应的字符串的方法。
class dog:
def __init__(self,name):
self.name = name
def run(self):
print("%s正在跑" % self.name)
d = dog("小黑")
c = input("Input function: ").strip()
print(hasattr(d,c)) #判断字符串是否在类的方法里面
#输出
True
getattr(object, name, default=None)
根据字符串去获取obj对象里的对应方法里的对应内存地址。
class dog:
def __init__(self,name):
self.name = name
def run(self):
print("%s正在跑" % self.name)
d = dog("小黑")
c = input("Input function: ").strip()
print(getattr(d,c))
getattr(d,c)()
#输出
<bound method dog.run of <__main__.dog object at 0x00000184E992E3C8>>
小黑正在跑
setattr(x, ‘y’, v)
动态给类装入一个方法。
def hit(self):
print("增加的一个hit方法")
class dog:
def __init__(self,name):
self.name = name
def run(self):
print("%s正在跑" % self.name)
d = dog("小黑")
c = input("Input function: ").strip()
setattr(dog,c,hit)
print(hasattr(d,c))
getattr(d,c)()
##输出
Input function: hit
True
增加的一个hit方法
delattr(x, y)
删除类中的方法/属性。

浙公网安备 33010602011771号