反射

反射:通过字符串映射到对象的属性

class People:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def talk(self):
        print("%s is talking" % self.name)

obj = People("egon",18)

内置方法

判断
print(hasattr(obj,"name"))  # 判断obj下面有没有.name这个属性,
# print(hasattr(obj,"talk")) # 两个参数,第一个是对象名或类名,第二个是字符串形式的属性名或方法名

#获取
print(getattr(obj,"name",None))
print(getattr(obj,"talk",None))

#改、新增
setattr(obj,"sex","male")  # obj.sex = "male"
print(obj.sex)

#
delattr(obj,"age")  # del obj.age
print(obj.__dict__)

反射的应用:

class Service:
    def run(self):
        while True:
            inp = input(">>>:").strip()  # inp = "get a.txt"
            cmd = inp.split( )   # cmd = ["get","a.txt"]
            if hasattr(self,cmd[0]):
                func = getattr(self,cmd[0])
                func(cmd)

    def get(self,cmd):
        print("get ......")

    def put(self,cmd):
        print("put ......")

obj = Service()
obj.run()
原文地址:https://www.cnblogs.com/nanjo4373977/p/12188318.html