Python 反射机制
一、反射的方法:
hasattr(obj,name_str):
getattr(obj,name_str):
setattr(obj,name_str,value):
delattr(obj,name_str):
二、方法的简单介绍:
getattr :
class User:
def __init__(self, username):
self.username = username
def get_user(self):
return self.username
u = User("Mouse")
method ="get_user"
if hasattr(u,method):
func = getattr(u,method)
print(func())
else:
print("操作有误,请重新输入")
>>>> 输出结果:
Mouse
setattr :
def hello(self):
print("hello 方法被调用了")
class User:
pass
u = User()
setattr(u,"hello",hello)
func = getattr(u,"hello")
func(u)
>>> 输出:
hello 方法被调用了
delattr :
class User:
def __init__(self,name):
self.name = name
def eat(self):
print('%s 正在吃夜宵 ...'%self.name)
def run(self):
print('%s 正在跑步中 ...'%self.name)
choice = input('>>>:')
c = User('胖毛')
print(c.name)
try:
if hasattr(c,choice):
delattr(c,choice)
else:
pass
print(c.name)
except AttributeError:
print('删除%s成功'%choice)