python之反射与异常处理
2018-01-28 16:49 yyshuke 阅读(181) 评论(0) 收藏 举报反射包括:hasattr(obj,str) getattr(obj,str) setattr(obj,y,z)相当于obj.y=z delattr(obj,str)
class Dog(object):
def __init__(self,name,age):
self.name=name
self.age=age
self.food='屎'
def eat(self):
print('%s 最喜欢吃%s'%(self.name,self.food))
d=Dog('刘涵宇',1)
choice=input('>>:').strip()
print(hasattr(d,choice))#判断d里是否含有对应的字符串的方法
print(getattr(d,choice))#获取D里对应的方法的内存地址
func=getattr(d,choice)
func()
2.没有输入的方法时,可以加方法
def bulk(self):
print('%s is yelling'%self.name)
class Dog(object):
def __init__(self,name,age):
self.name=name
self.age=age
self.food='屎'
def eat(self):
print('%s 最喜欢吃%s'%(self.name,self.food))
d=Dog('刘涵宇',1)
choice=input('>>:').strip()
if hasattr(d,choice):
func=getattr(d,choice)
func()
else:
setattr(d,choice,bulk)
d.talk(d)
异常处理就是用try和except
try:
pass
except keyerror as e:
pass
else:#没有异常时执行else
pass
finally:
pass
浙公网安备 33010602011771号