• 反射


    #通过字符串映射到对象的属性
    class People:
    county = 'china'
    def __init__(self, name, age):
    self.name = name
    self.age = age
    def take(self):
    print('%s is taking'%self.name)
    p = People('alex', 18)
    print(p.name)#打印name属性
    print(p.take)#打印绑定的方法

    # chice = input('>>>') #chice = 'name'
    # print(p.chice) #print(chice.''name'')
    #查询属性 结果为True或者False
    print(hasattr(p, 'name')) #判断有没有''name''这个属性,结果返回True或者False
    print(hasattr(p, 'take')) #判断有没有''take''这个函数属性,结果返回True或者False
    #查询属性,返回属性的值
    print(type(getattr(p, 'name', None))) #把字符串'''name'''当做属性name查询到属性name的值,如果没有name这个属性则返回None,前提是''name''后要加None参数
    print(getattr(p, 'take', None)) #查到一个绑定方法
    #设置增加修改属性,(以字符串形式)
    setattr(p, 'sex', 'male') #通过字符串形式添加设置新的属性
    print(p.sex) #打印通过字符串添加的属性
    #删除属性,(以字符串形式)
    delattr(p, 'age')
    print(p.__dict__)
    #同时以上四种方法不光可以用于对象还可以用于类
    print(getattr(People, 'county'))




    #反射的应用场景
    class Serive:
    def run(self):
    while 1:
    inp = input('>>>').strip() #get, a.txt
    cmds = inp.split(',') #[get, a.txtx]
    print(cmds)
    if hasattr(self, cmds[0]): #以字符串的get判断是否有get属性
    #print(getattr(self, cmds[0]))
    func = getattr(self, cmds[0])#查询字符串get属性并且赋值,此时字符串get等于函数get
    func(cmds) #调用get方法
    def get(self, cmds):
    print('get...')
    def put(self, cmds):
    print('put...')
    s = Serive()
    s.run()
  • 相关阅读:
    JavaScript与ajax的作用域问题
    Note
    理解C#反射
    秋季雾天驾驶注意安全
    开车撞车之后
    医保机构电话
    提前还贷四大细节需要注意
    请在这汽车内循环和外循环正确使用方法!你会用了吗?
    老外吐槽“娶中国老婆等于娶一家人”引共鸣
    车型与车主
  • 原文地址:https://www.cnblogs.com/yuexijun/p/10259176.html
Copyright © 2020-2023  润新知