反射的简单使用

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

反射使用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()
posted @ 2021-04-16 17:24  ty1539  阅读(38)  评论(0编辑  收藏  举报