码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象-反射

时间:2018-12-31 11:21:10      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:div   while   int   mds   inpu   class   one   sel   NPU   

反射:通过字符串映射到对象的属性
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()

 

面向对象-反射

标签:div   while   int   mds   inpu   class   one   sel   NPU   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!