自定义异常

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)


posted @ 2020-07-02 09:57  the3times  阅读(146)  评论(0编辑  收藏  举报