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

  可参考较好文章:https://www.cnblogs.com/kongk/p/8645202.html

posted @ 2018-03-27 12:03  耐烦不急  阅读(221)  评论(0编辑  收藏  举报