反射
1.反射:由字符串反向找变量、函数、类
案例:通过字符串反射类
import sys class Person(object): def __init__(self, name): self.name = name def eat(self, food): print("{}在吃{}".format(self.name, food)) def dream(self): print("{}在白日做梦!".format(self.name)) s = "person" # 首字母要大写 s = s.capitalize() print(s, type(s)) # 打印当前可用的变量 print(locals()['s']) print(locals().get("s")) # 反射 if hasattr(sys.modules[__name__], s): print("找到了") the_class = getattr(sys.modules[__name__], s) print(the_class) obj = the_class(name="张三") obj.eat("炒花甲")


浙公网安备 33010602011771号