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

  

最新文章

  1. GO语言之channel
  2. 学习使用 jQuery & CSS3 制作照片堆栈效果
  3. 网络请求之JSON解析
  4. js网页中调用本地应用程序
  5. c语言求平面上2个坐标点的直线距离、求俩坐标直线距离作为半径的圆的面积、递归、菲波那次数列、explode
  6. JAVA使用POI读取EXCEL文件的简单model
  7. hdu1715
  8. [BZOJ 3196] 213平衡树 【线段树套set + 树状数组套线段树】
  9. iOS原生refresh(UIRefreshControl)
  10. H5前端框架推荐合集
  11. 使用 after 伪类清除浮动
  12. leetcode 总结part1
  13. TensorRT学习总结
  14. world转.md
  15. Linux下的python等操作【转载】
  16. 《完美应用ubuntu》之全面管理ubuntu软件源
  17. css 样式 文字过长 换行处理方法
  18. wazhu之agent manage
  19. C++:借助tinyxml2读取XML文件
  20. iOS利用block实现链式编程方法(Objective-C链式编程)

热门文章

  1. 挨踢职场求生法则-----我在IT职场打滚超过15年了,从小小的程序员做到常务副总
  2. BCG使用
  3. AOP 应用
  4. 测试 | Mock object
  5. C#静态类、静态构造函数,类与结构体的比较
  6. python 基础(九) 文件操作
  7. 转 载python数据分析(1)-numpy产生随机数
  8. Codeforces Round #497 (Div. 2) A. Romaji
  9. springMVC-上传图片
  10. SSAS中雪花模型