python 的反射详解

def bulk(self):
print('%s is barking'%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("zhangye")
choice = input(">>:").strip()

# print(hasattr(d,choice))#hasattr(obj,name_str)判断一个对象obj里是否有对应的name_str字符串的方法映射
# print(getattr(d,choice))#getattr(obj,name_str)根据字符串去获取obj对象里的对应的方法的内存地址,加括号调用
if hasattr(d,choice)== True:
#删除
delattr(d,choice)

#调用
# f=getattr(d,choice)
# f("baozi")
#更改变量值
# attr = getattr(d, choice)
# setattr(d,choice,"able_test")#更改变量值

else:
# setattr(d,choice,bulk)
# d.talk(d)
setattr(d,choice,22)#setattr(x, 'y', v) is equivalent to ``x.y = v''
print(getattr(d,choice))

print(d.name)
,加括号调用
posted @ 2020-07-16 22:14  安好_世界  阅读(148)  评论(0编辑  收藏  举报