Python中自定义输出类型()

时间:2013-10-13 14:39:03

标签: python magic-methods

如何根据班级自定义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'>'

2 个答案:

答案 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)))