zoukankan      html  css  js  c++  java
  • python_110_反射

    class Dog(object):
        def __init__(self,name):
            self.name=name
        def eat(self):
            print('%s is eating '%self.name)
    d=Dog('jingjing')
    choice1=input('>>:').strip()#输入方法
    print(hasattr(d,choice1))#查看是否有该方法
    print(getattr(d,choice1))#返回的是内存对象地址
    getattr(d,choice1)()#获得方法
    
    
    def bulk(self):
        print('%s is yelling....'%self.name)
    class Dog(object):
        def __init__(self,name):
            self.name=name
        def eat(self,food):
            print('%s is eating %s'%(self.name,food))
    d=Dog('晶晶')
    choice2=input('>>:').strip()
    if hasattr(d,choice2):
        func=getattr(d,choice2)
        func('肉')
    else:
        setattr(d,choice2,bulk)
        #d.talk(d)#d.talk=bulk,可以和函数名不一样,但是输入的时候要输入talk。正常是d.bulk(d)。可以将本句改成以下方式,输入bulk或者talk都行
        func=getattr(d,choice2)
        func(d)
    
    class Dog(object):
        def __init__(self,name):
            self.name=name
        def eat(self,food):
            print('%s is eating %s'%(self.name,food))
    d=Dog('qinqin')
    choice3=input('>>:').strip()
    if hasattr(d,choice3):
        func=getattr(d,choice3)
        func('肉')
    else:
        setattr(d,choice3,22)#可以随便输入(静态属性),直接返回的是22     注意:不能输入name,name是原有的属性
        print(getattr(d,choice3))
    
    class Dog(object):
        def __init__(self,name):
            self.name=name
        def eat(self,food):
            print('%s is eating %s'%(self.name,food))
    d=Dog('qinqin')
    choice4=input('>>:').strip()
    if hasattr(d,choice4):
        attr=getattr(d,choice4)
        setattr(d,choice4,'chenchen')#可以输入name了
    else:
        setattr(d,choice4,22)#
        print(getattr(d,choice4))
    print(d.name)
    
    
    class Dog(object):
        def __init__(self,name):
            self.name=name
        def eat(self,food):
            print('%s is eating %s'%(self.name,food))
    d=Dog('qinqin')
    choice5=input('>>:').strip()
    if hasattr(d,choice5):
        delattr(d,choice5)
    print(d.name)#输入name,出错,打印不出来,已经删除
    '''
    反射:
        hasattr(obj,name_str),判断对象obj里是否有对应的name_str字符串的方法
        getattr(obj,name_str),根据字符串去获取obj对象里的对应的方法的内存地址
        setattr(obj,'y',z)相当于 obj.y=z,通过字符串添加新的属性或方法
        delattr删除一个属性
    用处:动态内存装配
    '''
    

      

  • 相关阅读:
    结对项目电梯调度--设计模拟
    程序的单元测试
    一个文本单词统计的案例
    MFC vs2012 Office2013 读写excel文件
    Unix NetWork Programming(unix环境编程)——环境搭建(解决unp.h等源码编译问题)
    VMware三种上网模型
    矩阵求逆算法及程序实现(C++)
    unix环境高级编程基础知识之第四章
    2014阿里研发面试题目
    MFC下debug改成release版本出现问题及解决办法
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/8656741.html
Copyright © 2011-2022 走看看