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删除一个属性
    用处:动态内存装配
    '''
    

      

  • 相关阅读:
    iOS开发——Autolayout下动态调整单元格高度
    iOS开发——随机数的使用
    iOS开发——使用基于Autolayout的ScrollView
    获取OS X中App Store更新后的安装包(如XCode)
    iOS开发——使用Autolayout弹出键盘
    iOS开发——给ImageView添加点击事件
    iOS开发——NSIBPrototypingLayoutConstraint原型约束造成的莫名问题
    iOS开发——异常:[__NSCFNumber length]: unrecognized selector sent to instance
    iOS开发——检测屏幕旋转
    iOS开发——使用Autolayout生成动态高度的TableViewCell单元格
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/8656741.html
Copyright © 2011-2022 走看看