python学习,day7 反射

反射
hasattr(obj,name_str) , 判断一个对象obj里是否有对应的name_str字符串的方法
getattr(obj,name_str), 根据字符串去获取obj对象里的对应的方法的内存地址
setattr(obj,'y',z), is equivalent to ``x.y = v''
delattr 删除属性或者方法
# coding=utf-8
# Author: RyAn Bi

def bulk(self):
    print('%s is calling'%self.name)

class Dog(object):
    def __init__(self,name):
        self.name = name


    def eat(self,some):
        print('%s is eating %s'%(self.name,some))


d= Dog('abc')
choice = input('>>:').strip()
#print(hasattr(d,choice))   #判断dog里是否有choice赋值的属性
#print(getattr(d,choice))   #获取dog里的choice的属性
if hasattr(d,choice):
    func = getattr(d,choice)
    func('dce')
else:
    #setattr(d,choice,bulk)    #输入talk,新建了一个方法
    #d.talk(d)

    setattr(d,choice,22)   #新建了一个属性 getattr(d,choice) = 22
    print(getattr(d,choice))

  

原文地址:https://www.cnblogs.com/bbgoal/p/13225635.html