[英]Custom Ouput of type() in Python
如何针对我的类自定义type()
调用的输出?
我正在类中实现__add__
方法。 如果用户尝试使用它不正确,我将TypeError
并显示以下消息:
err_msg = "unsupported operand type(s) for -: '{}' and '{}'"
raise TypeError(err_msg.format(type(self), type(other)))
输出为:
TypeError: unsupported operand type(s) for +: '<type 'instance'>' and '<type 'int'>'
我需要做什么来读取'<type 'my_class'>'
?
您不想更改返回的type
。 您想使您的类成为一种新的类(除了许多其他优点),这意味着该类对象的字符串表示形式将提及其名称,就像所有适当的类型(包括但不限于内置)一样。 更改
class my_class:
...
至
class my_class(object):
...
如果my_class
从另一个类,这是旧式自己继承,使该类新stlye代替。
简单的答案是不要对my_class使用type()
,而应使用字符串:
raise TypeError(err_msg.format("<type 'my_class'>", type(other)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.