zoukankan      html  css  js  c++  java
  • 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.....
    
  • 相关阅读:
    8086汇编学习小记王爽汇编语言实验12
    8086汇编学习小记王爽汇编语言课程设计1
    activeMQ 持久化配置 kevin
    snmpwalk kevin
    tcp benchmark kevin
    apache camel 条件路由 kevin
    netty 并发访问测试配置 kevin
    snmp常见操作 kevin
    转发:RocketMQ与kafka的对比 kevin
    centos jdk 下载 kevin
  • 原文地址:https://www.cnblogs.com/friday69/p/9386005.html
Copyright © 2011-2022 走看看