如何在python中将实例转换为String类型?

时间:2016-03-06 04:38:39

标签: python string instance

对于课程printHello,类实例为Hello 现在当我执行下面的代码时 print printHello
输出为"HelloPrinted"
现在我想将printHello与字符串类型进行比较,但由于printHello是类型实例,因此无法实现。 有没有办法捕获print printHello代码的输出并将其用于比较或将printHello的类型转换为字符串,我可以将其用于其他字符串比较? 任何帮助表示赞赏。

4 个答案:

答案 0 :(得分:2)

如果你想专门比较字符串,你可以用两种不同的方式来做。首先是为您的班级定义__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"

答案 1 :(得分:1)

在Hello类中定义 str repr

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

答案 2 :(得分:1)

为此目的,应在您的类中定义一个特殊的方法__repr__:

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

    def __repr__(self):
        return "printHello"

答案 3 :(得分:0)

我想你想要:

string_value = printHello.__str__()

if string_value == "some string":
  do_whatever()

__str__()使用print方法来理解类对象。