面向对象-反射

时间:2018-12-31 10:58:23   收藏:0   阅读:136
反射:通过字符串映射到对象的属性
class People:
    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(obj.name)
print(obj.talk)

choice=input(>>>)

print(hasattr(obj,name)) # 判断有没有
print(hasattr(obj,talk))
print(getattr(obj,namex,None)) #获取

setattr(obj,sex,male) # obj.sex=‘male修改
print(obj.sex)

delattr(obj,age) #删除
print(obj.__dict__)

 

class Service:
    def run(self):
        while True:
            cmd=input(>>>).strip()
            if hasattr(self,cmd):
                # print(‘get‘)
                func=getattr(self,cmd)
                func()
    def get(self):
        print(get....)

    def put(self):
        print(put....)


obj=Service()
obj.run()

class Service:
    def run(self):
        while True:
            cmd = input(>>>)
            cmds = cmd.split()
            print(cmds)
            if hasattr(self,cmds[0]):
                func=getattr(self,cmds[0])
                func()

    def get(self):
        print(get....)

    def put(self):
        print(put....)


obj=Service()
obj.run()

 

原文:https://www.cnblogs.com/hexiaorui123/p/10201474.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!