zoukankan      html  css  js  c++  java
  • 反射的简单使用

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

    反射使用1

    class s2:
        def f1(self):
            print('打印首页')
            return '首页'
    
        def f2(self):
            print('打印新闻')
            return '新闻'
    
        def f3(self):
            print('打印精华')
            return '精华'
    
        print('类s2启动了成功了')
    
    inp = input('请输入要查看的URL:')
    if hasattr(s2,inp):
        func = getattr(s2,inp)
        print('这是func: ',func,'你好啊')
        result = func('self')
        print('打印result: ',result)
    else:
        print('404')
    

    反射使用2

    class People:
        country = 'China'
        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('age',hasattr(obj,'age'))
    print('name',hasattr(obj,'name'))
    print('talk',hasattr(obj,'talk'))
    print('talk5',hasattr(obj,'talk5'))
    
    print('talk',getattr(obj,'talk',1),getattr(obj,'talk',1)())
    print('talk1',getattr(obj,'talk1',1))
    print('name5',getattr(obj,'name5',None))
    setattr(obj,'age',22)
    setattr(obj,'sex','male')
    print(obj.age,obj.sex)
    print(obj.__dict__)
    delattr(obj,'age')
    print(obj.__dict__)
    print(hasattr(People,'country1'))
    print(getattr(People,'country'))
    输出:
    age True
    name True
    talk True
    talk5 False
    talk <bound method People.talk of <__main__.People object at 0x0000000009FE6898>>
    talk1 1
    name5 None
    22 male
    {'name': 'egon', 'age': 22, 'sex': 'male'}
    {'name': 'egon', 'sex': 'male'}
    False
    China
    

    使用2:

    class Service:
        def run(self):
            while True:
                inp = input('>>>:').strip()
                cmds = inp.split()  #  cmds = [get,a.txt]
                print(inp,type(inp),type(cmds),cmds)
                if hasattr(self,cmds[0]):
                    # func=getattr(self,cmd)
                    # func()
                    getattr(self, cmds[0])(cmds)
    
        def get(self,cmds):
            print('get,,,,',cmds)
    
        def put(self,cmds):
            print('put,,,,',cmds)
    obj = Service()
    obj.run()
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    [转] s3c6410开发板研究笔记(一)从SD卡启动UBOOT(未完待续。。。)
    [转]解决aptget f install提示错误
    ubuntu 软件中心崩溃解决办法
    [转]Linux环境下Jlink配置
    [转]SD卡引脚 电路图及工作原理介绍
    [原]linux下安装运行supervivitransfertool
    [转]OclO 开发笔记
    [转]dnw for linux
    [转]使用JLink间接烧写uboot,supervivi到mini2440的方法
    Js 浏览器全屏代码(按F11)
  • 原文地址:https://www.cnblogs.com/heris/p/14014785.html
Copyright © 2011-2022 走看看