python-魔法函数-__str__ __repr__ 的一次异常
# encoding: utf-8
import logging
ERROR_NOT_FOUNDED_FILE = "error_not_founded_file"
class GeneralError(Exception):
def __init__(self, value, description):
print("GeneralError __init__")
self.value = value
self.description = description
def __repr__(self):
print("__repr__")
return "<{} {}:{}>".format(self.__class__.__name__, self.value, self.description)
def __str__(self):
print("__str__")
return "<{} {}:{}>".format(self.__class__.__name__, self.value, self.description)
class FileError(GeneralError):
def __init__(self, description):
super(FileError, self).__init__(ERROR_NOT_FOUNDED_FILE, description)
def __repr__(self):
return super(FileError, self).__repr__() # 不规范
def __str__(self):
super(FileError, self).__str__() # 会报错
try:
raise FileError('file error')
except Exception as e:
logging.info(f"exec error: {e}")
print("补救措施!")
执行结果如下:
错误:
__str__ returned non-string (type NoneType) 可以看出,e返回了None。
debug:
def __str__(self):
super(FileError, self).__str__() # 调用了,父类的__str__函数,没有返回(也可以理解为返回了None)。
logging.info(f"exec error: {e}") # 调用了FileError().__str__,没有返回值,自然就报错了。
修复:
def __str__(self):
return super(FileError, self).__str__() # 调用了,父类的__str__函数,返回执行结果。
或者
不实现重写__str__。
那么正常的代码应该是:
# encoding: utf-8
import logging
ERROR_NOT_FOUNDED_FILE = "error_not_founded_file"
class GeneralError(Exception):
def __new__(cls, *args, **kwargs):
print("GeneralError __new__")
return super(GeneralError, cls).__new__(cls)
def __init__(self, value, description):
print("GeneralError __init__")
self.value = value
self.description = description
def __repr__(self):
print("__repr__")
return "<{} {}:{}>".format(self.__class__.__name__, self.value, self.description)
def __str__(self):
print("__str__")
return "<{} {}:{}>".format(self.__class__.__name__, self.value, self.description)
class FileError(GeneralError):
def __init__(self, description):
super(FileError, self).__init__(ERROR_NOT_FOUNDED_FILE, description)
def __repr__(self):
return super(FileError, self).__repr__()
# 我选择不重写!!! 唯一的修改
# def __str__(self):
# super(FileError, self).__str__()
try:
raise FileError('file error')
except Exception as e:
logging.info(f"exec error: {e}")
print("补救措施!")
当然,这个环境里,代码能跑了。不过,能跑是能跑,有一处不规范
def __repr__(self):
print("__repr__")
return "<{} {}:{}>".format(self.__class__.__name__, self.value, self.description)
官方文档对于__repr__的解释是(repr会调用对象的__repr__):
def repr(obj): # real signature unknown; restored from __doc__
"""
Return the canonical string representation of the object. For many object types, including most builtins, eval(repr(obj)) == obj.
"""
pass
很显然:
err = FileError("file error")
eval(repr(err)) == err
File "E:/coding/hello.py", line 53, in <module>
eval(repr(err)) == err
File "<string>", line 1
<FileError error_not_founded_file:file error>
^
SyntaxError: invalid syntax
所以,要修改代码为:
def __repr__(self):
print("__repr__")
return "{}('{}')".format(self.__class__.__name__, self.description)
那么,最终的代码应该是:
# encoding: utf-8
import logging
ERROR_NOT_FOUNDED_FILE = "error_not_founded_file"
class GeneralError(Exception):
def __new__(cls, *args, **kwargs):
print("GeneralError __new__")
return super(GeneralError, cls).__new__(cls)
def __init__(self, value, description):
print("GeneralError __init__")
self.value = value
self.description = description
def __repr__(self):
print("__repr__")
return "{}('{}')".format(self.__class__.__name__, self.description) # 第一处修改: 返回字符串格式修改
def __str__(self):
print("__str__")
return "<{} {}:{}>".format(self.__class__.__name__, self.value, self.description)
class FileError(GeneralError):
def __init__(self, description):
super(FileError, self).__init__(ERROR_NOT_FOUNDED_FILE, description)
# 第二处修改:不重写父类方法
# def __repr__(self):
# return super(FileError, self).__repr__()
# def __str__(self):
# super(FileError, self).__str__()
try:
raise FileError('file error')
except Exception as e:
logging.info(f"exec error: {e}")
print("补救措施!")
err = FileError("file error")
eval(repr(err)) == err
python-魔法函数-__str__ __repr__ 的一次异常的更多相关文章
- python魔法函数__dict__和__getattr__的妙用
python魔法函数__dict__和__getattr__的妙用 __dict__ __dict__是用来存储对象属性的一个字典,其键为属性名,值为属性的值. 既然__dict__是个字典那么我们就 ...
- Python魔法函数与两比特量子系统模拟
技术背景 本文主要涵盖两个领域的知识点:python的魔法函数和量子计算模拟,我们可以通过一个实际的案例来先审视一下这两个需求是如何被结合起来的. 量子计算模拟背景 ProjectQ是一个非常优雅的开 ...
- 复习python的__call__ __str__ __repr__ __getattr__函数 整理
class Www: def __init__(self,name): self.name=name def __str__(self): return '名称 %s'%self.name #__re ...
- Python魔法函数
python中定义的以__开头和结尾的的函数.可以随意定制类的特性.魔法函数定义好之后一般不需要我们自己去调用,而是解释器会自动帮我们调用. __getitem__(self, item) 将类编程一 ...
- python基础---- __getattribute__----__str__,__repr__,__format__----__doc__----__module__和__class__
目录: 一. __getattribute__ 二.__str__,__repr__,__format__ 三.__doc__ 四.__module__和__class__ 一. __getattri ...
- python魔法函数之__getattr__与__getattribute__
getattr 在访问对象的属性不存在时,调用__getattr__,如果没有定义该魔法函数会报错 class Test: def __init__(self, name, age): self.na ...
- python魔法函数(二)之__getitem__、__len__、__iter__
魔法函数会增强python类的类型,独立存在 __getitem class Company: def __init__(self, employees): self.employees = empl ...
- python魔法函数的一些疑问
看了魔法函数,有一点疑问.1中需要用self.word才能执行,而2直接用self就可以执行.而1中Word继承了int基本类型,但在__new__时并没有什么卵用.当用 Word(“123”)来实例 ...
- raindi python魔法函数(一)之__repr__与__str__
__repr__和__str__都是python中的特殊方法,都是用来输出实例对象的,如果没有定义这两个方法在打印的时候只会输出实例所在的内存地址 这种方式的输出没有可读性,并不能直观的体现实例.py ...
- Python——详解__str__, __repr__和__format__
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是Python专题的第10篇文章,我们来聊聊Python当中的类. 打印实例 我们先从类和对象当中最简单的打印输出开始讲起,打印一个实例 ...
随机推荐
- 项目中pom.xml的某些坐标无法加载
项目中pom.xml的某些坐标无法加载 maven官方查找对应的坐标文件下载 https://mvnrepository.com/artifact/com.fasterxml.jackson.core ...
- 集群笔记-fence
fence机制: 隔离主机到存储的连接 配置fence_xvm步骤 KVM fence 请问物理机器需要真实的fence 设备吗? 否 一.将物理机器(宿主机)f0配置成fence设备 1. 安装fe ...
- web server 接口调用测试
1.新建工程 ,鼠标右击new 2.设置web server接口访问链接,然后下一步 生成代码 3.生成客户端代码 4.创建测试类 调用服务
- vscode调试openresty
一.快速上手 1.软件下载 官网地址:https://code.visualstudio.com/ 安装视频:https://code.visualstudio.com/docs/getstarted ...
- JAVA随机获取集合里的元素
@Test public void aaa(){ String[] sbNo = new String[]{"asd","asd","asd" ...
- Typora中的emoji表情
People :smile: :laughing: :tired_face: :blush: :smiley: ️ :relaxed: :smirk: :heart_eyes: :ki ...
- 用Flask+Element+Vue搭建md5、sha加密网站
目录 一.绘制网站页面 1.1 绘制输入框 1.2 绘制表单 二.flask后端接口 三.前后端数据交互 在本章中,我们能学到: 1.Element 中的输入框.按钮.消息提示组件的使用 2.axio ...
- FFT简单概述
概念 快速傅里叶变换 (fast Fourier transform), 即利用计算机计算离散傅里叶变换(DFT)的高效.快速计算方法的统称,简称FFT.快速傅里叶变换是1965年由J.W.库利和T. ...
- vue后台管理系统
1. 项目概述: 根据不同的应用场景,电商系统一般都提供了 PC 端.移动 APP.移动 Web.微信小程序等多种终端访问方式. 2. 电商后台管理系统的功能 电商后台管理系统用于管理用户账号.商品分 ...
- Pytest+allure+requests接口自动化
实现功能 测试数据隔离: 测试前后进行数据库备份/还原 接口直接的数据依赖: 需要B接口使用A接口响应中的某个字段作为参数 对接数据库: 讲数据库的查询结果可直接用于断言操作 动态多断言: 可(多个) ...