python之反射实例 setattr delattr
作者:互联网
# __*__ coding: utf-8 __*____author__ = "David.z"def bulk(self):print("%s is yelling..."%self.name)class Dog(object):def __init__(self,name): self.name = namedef eat(self,food):print(" %s is eating..."%self.name,food) d = Dog("Alex") choice = input(">>:").strip()if (hasattr(d,choice)):#反射 delattr(d,choice)# attr=(getattr(d,choice))# # print(attr)# # func("ChrnRonghua")# setattr(d,choice,"Ronghua")else:# setattr(d,choice,bulk)# d.talk(d) setattr(d,choice,None)print(getattr(d,choice))print(d.name)'''反射 hasattr(obj,name_str) ,判断一个对象obj里是否有对应的name_str字符串的方法 getattr(obj,name_str),根据字符串去获取obj对象里的对应的方法的内存地址 setattr(obj,'y',z),is eauivalent ot "x.y = v" delattr 删除'''
标签:__,delattr,obj,name,setattr,python,self,choice,print 来源: https://blog.51cto.com/3180829/2681056