zoukankan      html  css  js  c++  java
  • 面向对象-反射

    编辑本随笔

    当调用一个类中不存在得属性或方法,类默认调用__getarrt__()方法,可以自定义

    def test():
        print("Test")
    
    T={"six":test}
    
    class Student(object):
        def __init__(self,name,age):
            self.name=name
            self.age=age
        def __getattr__(self, item):
            if item in T:
                return T[item]
    s=Student('y',18)
    print(s.six)
    s.six()

    反射:通过字符串映射到对象的属性,该方法实用于对象与类

    hasattr(obj,'name')

    class People:
        def __init__(self,name,age):
            self.name=name
            self.age=age
        def talk(self):
            print("%s is talking" % self.name)
    obj=People('ya',22)
    #判断对象obj下面有没有obj.name属性
    print(hasattr(obj,'name'))
    print(hasattr(obj,'talk'))

    getattr(obj,'str','defaultstr')拿到对象属性

    print(getattr(obj,'name',None))
    print(getattr(obj,'talk',None))

    setattr(obj,'sex','male')设置对象属性

    setattr(obj,'sex','male')
    print(obj.sex)

    delattr(obj,'str')删除对象属性

    print(obj.__dict__)
    delattr(obj,'age')
    print(obj.__dict__)

    反射的应用

    class service:
        def run(self):
            while True:
                inp=input(">>:").strip()
                cmds=inp.split()
                if hasattr(self,cmds[0]):
                    func=getattr(self,cmds[0])
                    func(cmds)
        def get(self,cmds):
            print("get......",cmds)
        def put(self,cmds):
            print("put......",cmds)
    obj=service()
    obj.run()

  • 相关阅读:
    3.6
    2.26
    2.22
    出差记录(每日食谱)
    关于本博客的样式
    知乎搜索/(引擎)的故事
    【历史/对越自卫反击战】刘立华||我的战地笔记——陵园祭
    如何在Xpath路径中添加变量?如何将字符串传递给Xpath?
    阿里网盘搜索网站汇总
    经济学人下载
  • 原文地址:https://www.cnblogs.com/yaya625202/p/8887999.html
Copyright © 2011-2022 走看看