繁体   English   中英

Python中type()的自定义输出

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM