自定义异常
class MyException(Exception):
def __init__(self, error_info):
self.error_info = error_info
def __str__(self):
return self.error_info # 给as 后面的变量
class Person(object):
def __setattr__(self, key, value):
if not isinstance(value, str):
raise MyException('使用必须是字符串')
# self.__dict__[key] = value
super().__setattr__(key, value)
p = Person()
try:
p.name = 18
except MyException as e:
print(e)