通过字符串的形式进行操作对象的属性方法
1.getattr获取对象属性及方法
class oe:
def __init__(self,name,age,gerden):
self.name = name
self.age = age
self.gerden = gerden
def eat(self):
print(f"{self.name}在吃烤肉")
def sleep(self):
print(f"{self.name}在睡觉")
xm = oe("小明",18,"男")
n = getattr(xm,'name')
print(n)
a = getattr(xm,"eat")
a()
height = getattr(xm,'height',1.8)
print(height)
2.setattr设置对象属性
class oe:
def __init__(self,name,age,gerden):
self.name = name
self.age = age
self.gerden = gerden
def eat(self):
print(f"{self.name}在吃烤肉")
def sleep(self):
print(f"{self.name}在睡觉")
xm = oe("小明",18,"男")
print(xm.age)
setattr(xm,'age',18)
print(xm.age)
3.hasattr判断对象是否有对应的属性及方法
class oe:
def __init__(self,name,age,gerden):
self.name = name
self.age = age
self.gerden = gerden
def eat(self):
print(f"{self.name}在吃烤肉")
def sleep(self):
print(f"{self.name}在睡觉")
xm = oe("小明",18,"男")
print(hasattr(xm,'height'))
print(hasattr(xm,'name'))
print(hasattr(xm,'age'))
print(hasattr(xm,'run'))
4.delattr删除对象属性
class oe:
def __init__(self,name,age,gerden):
self.name = name
self.age = age
self.gerden = gerden
def eat(self):
print(f"{self.name}在吃烤肉")
def sleep(self):
print(f"{self.name}在睡觉")
xm = oe("小明",18,"男")
delattr(xm,'age')
print(xm.age)
class user:
def reg(self):
print("注册功能")
def log(self):
print("登录功能")
def shop(self):
print("购买功能")
def get(self):
print("取钱")
xm = user()
co = input("请输入你要操作的功能:")
if hasattr(xm,co):
fun = getattr(xm,co)
fun()
else:
print("输入有误!")
异常:就是在程序执行过程中有逻辑等的其他错误终止程序运行
异常处理:在程序中,将感觉有问题的代码进行处理,让程序运行时,不为因其错误而终止
1.语法错误:syntaxerror
2.逻辑错误:nameerror 没定义
typeerror 类型错误
indexerror 下标超出范围
keyerror
注:错误还有很多种
# 下标超出
res = '小明在上课'
print(res[10])
# 捕获异常错误
res = '小明在上课'
try:
print(res[10])
except IndexError as msg:
print("解决报错")
print(msg)
# 可以捕获任何异常
res = '小明在上课'
try:
print(res[10])
except Exception :
print("解决报错")
发送AssertionError异常错误
主要是发送在判断表达式中
#当表达式不成立,不继续往下
x = 100
y = 300
assert x > y,'你做错了'
res = '小明在喝酒'
assert '不' in res, '在不在'
print('您好,请支付100元')
money = int(input('请输入:'))
if money < 100:
# 定义异常
raise Exception(f"money小于100,当前money为{money},交易失败")
elif money > 100:
print(f"返回金额{money - 100}")
else:
print('交易成功。')