#Author:lei
def bulk(self):
print("%s is yielling..."%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("niuhanyang")
choice=input(">>:").strip()
print(hasattr(d,choice)) #判断输入的 choice值是不是在d对象里对应的方法字符,在就为true
#print(getattr(d,choice)) #映射出chioce对应的对象内存地址
#getattr(d,choice)() #加上括号就是调用对象里 eat的方法,choice值=eat字符
#if hasattr(d,choice): #判断 choice值和eat字符对应
# getattr(d,choice)() #调用 d.eat() 获取对象内存地址,调用对象内存地址执行对象
if hasattr(d,choice):
# delattr(d,choice) 删除实例变量或方法,后面不在引用 比如 d,eat 后面就不能用d.eat()
func=getattr(d,choice)
func("baozi") #baozi对应food
else:
setattr(d,choice,bulk) #将d对象外面的bulk方法添加到d里的对象方法, 相当于外面的方法动态装备到类里
d.talk(d) #d对象添加bulk之后将方法重命名为talk,运行talk需要传d对象进去,相当于外面的方法动态装备到类里
#----------------------------------------------------
def bulk(self):
print("%s is yielling..."%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("niuhanyang")
choice=input(">>:").strip()
print(hasattr(d,choice)) #判断输入的 choice值是不是在d对象里对应的方法字符,在就为true
#print(getattr(d,choice)) #映射出chioce对应的对象内存地址
#getattr(d,choice)() #加上括号就是调用对象里 eat的方法,choice值=eat字符
#if hasattr(d,choice): #判断 choice值和eat字符对应
# getattr(d,choice)() #调用 d.eat() 获取对象内存地址,调用对象内存地址执行对象
if hasattr(d,choice): #判断 如果是否存在 判断name
# attr=getattr(d,choice) #获取对象内存地址
setattr(d,choice,"Ronghua") #那么就改成"Ronghua",name是存在的,那么 d.name="Ronghua" 设置修改name
#变量不能调用,只能引用
else:
setattr(d,choice,22) #新创建的变量赋值22,所以返回22,变量名是动态的,固定值22
#func=getattr(d,choice) 如果22是函数名
#func(d)
print(getattr(d,choice))
print(d.name) #setattr(d,choice,"Ronghua") #输入的choice如果为name,就对应为"Ronghua"
反射
原创
©著作权归作者所有:来自51CTO博客作者leiwenbin627的原创作品,请联系作者获取转载授权,否则将追究法律责任
下一篇:异常处理
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Java反序列化-反射
java反序列化之-反射
java 反序列化 web安全