如何根据班级自定义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'>'
?
答案 0 :(得分:3)
您不想更改type
返回的内容。您希望使您的类成为一种新的类(除了许多其他优点之外)意味着此类对象的字符串表示将提及其名称,如所有适当的类型(包括但不限于内置)。变化
class my_class:
...
到
class my_class(object):
...
如果my_class
继承自另一个旧式的类,请改为那个类new-stlye。
答案 1 :(得分:0)
简单的回答是不要将type()
用于my_class,而是使用字符串:
raise TypeError(err_msg.format("<type 'my_class'>", type(other)))