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()
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    Android Jetpack之WorkManager: 观察结果
    解决'androidx.arch.core:core-runtime' has different version for the compile (2.0.0) and runtime (2.0.1)
    我要研究一下minio,管理大量的照片
    分发消息的写法
    百度地图坐标转换
    HighChart 实现从后台取数据来实时更新柱状和折线组图
    导出Excel
    Java 8新特性之集合
    java中的Switch case语句
    提问:"~"运算符
  • 原文地址:https://www.cnblogs.com/heris/p/14014785.html
Copyright © 2011-2022 走看看