在python中如何将实例转换为字符串类型?

2024-06-25 23:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

假设类实例是类的printHello
现在当我执行下面的代码时
print printHello
输出是"HelloPrinted"
现在我想将printHello与字符串类型进行比较,但由于printHello属于实例类型,因此无法实现它。 是否有方法捕获print printHello代码的输出并将其用于比较,或者将printHello类型转换为字符串,我可以将其用于其他字符串比较? 如有任何帮助,我们将不胜感激。


Tags: 实例方法字符串代码类型printhelloprintedprinthello
3条回答

如果你想特别地比较字符串,你可以用两种不同的方法。首先是定义类的__str__方法:

class Hello:
    def __init__(self, data="HelloWorld"):
        self._data = data
    def __str__(self):
        return self._data

然后可以将字符串与以下项进行比较:

h = Hello()
str(h) == "HelloWorld"

或者您可以特别使用__eq__特殊函数:

class Hello:
    def __init__(self, data="HelloWorld"):
        self._data = data
    def __str__(self):
        return self._data
    def __eq__(self, other):
        if isinstance(other, str):
            return self._data == other
        else:
            # do some other kind of comparison

然后您可以执行以下操作:

h = Hello()
h == "HelloWorld"

在Hello类中定义str或repr

更多信息-https://docs.python.org/2/reference/datamodel.html#object.str

为此,应该在类中定义一个特殊的方法repr:

class Hello:
    def __init__(self, name):
        self.name= name

    def __repr__(self):
        return "printHello"

相关问题 更多 >