Python—面向对象05 反射

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

class People:
    country='China'

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

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


p = People("gd", 22)
print(p.name)  # p.__dic__['name']
print(p.talk)  # <bound method People.talk of <__main__.People object at 0x00000000027B7470>>


print(hasattr(p, 'name'))  # True 判断 对象p 里有没有 name 属性, hasattr(),第一个参数传对象,第二个参数传 属性名
print(hasattr(p, 'talk1'))  # True

print(getattr(p, 'name'))  # gd  拿到 对象 p 里的属性
# print(getattr(p, 'name2')) # AttributeError: 'People' object has no attribute 'name2'
# getattr(), 没有相应属性的时候,会报错,我们可以传入第三个参数
print(getattr(p, 'name2', None))  # None  这样,找不到属性的时候就会返回 None 了


setattr(p, 'sex', '机器大师')
print(p.sex)  # 机器大师


print(p.__dict__)  # {'name': 'gd', 'age': 22, 'sex': '机器大师'}
delattr(p, 'sex')  # 删除属性
print(p.__dict__)  # {'name': 'gd', 'age': 22}


# hasattr()  getattr()   setatter()  delattr() 不仅适用于对象,也可以用于类
print(hasattr(People, 'country'))  # True
print(getattr(People, 'country'))  # China

反射的应用

class Service:
    def run(self):
        while True:
            cmd = input(">>:").strip()
            if hasattr(self, cmd):
                func = getattr(self, cmd)
                func()

    def get(self):
        print('get......')

    def put(self):
        print('put.....')


obj = Service()
obj.run()

# >>:get
# get......
# >>:put
# put.....
原文地址:https://www.cnblogs.com/friday69/p/9386005.html