zoukankan      html  css  js  c++  java
  • 反射

    #通过字符串映射到对象的属性
    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()
  • 相关阅读:
    深港DJ好听的歌曲
    电调的相关知识
    CAD画图技巧经验
    第一期周二航拍视频分享 2017/07/10
    网站资料
    如何读懂零件图
    航拍技巧经验总汇
    乐迪AT9
    机器学习、数据挖掘、计算机视觉等领域经典书籍推荐
    Eclipse调试Java程序技巧
  • 原文地址:https://www.cnblogs.com/yuexijun/p/10259176.html
Copyright © 2011-2022 走看看