python_110_反射
2024-09-04 20:54:57
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删除一个属性
用处:动态内存装配
'''
最新文章
- GO语言之channel
- 学习使用 jQuery &; CSS3 制作照片堆栈效果
- 网络请求之JSON解析
- js网页中调用本地应用程序
- c语言求平面上2个坐标点的直线距离、求俩坐标直线距离作为半径的圆的面积、递归、菲波那次数列、explode
- JAVA使用POI读取EXCEL文件的简单model
- hdu1715
- [BZOJ 3196] 213平衡树 【线段树套set + 树状数组套线段树】
- iOS原生refresh(UIRefreshControl)
- H5前端框架推荐合集
- 使用 after 伪类清除浮动
- leetcode 总结part1
- TensorRT学习总结
- world转.md
- Linux下的python等操作【转载】
- 《完美应用ubuntu》之全面管理ubuntu软件源
- css 样式 文字过长 换行处理方法
- wazhu之agent manage
- C++:借助tinyxml2读取XML文件
- iOS利用block实现链式编程方法(Objective-C链式编程)