简体   繁体   English

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

[英]How to convert an instance into String type in python?

say class instance is printHello for class Hello 说类实例是类Hello printHello
Now when I execute below code 现在,当我执行以下代码时
print printHello
The output is "HelloPrinted" 输出为"HelloPrinted"
Now I want to compare the printHello with a string type and cannot achieve it because printHello is of type instance. 现在,我想将printHello与字符串类型进行比较,但由于printHello是实例类型,因此无法实现。 Is there a way to capture the output of print printHello code and use it for comparison or convert the type of printHello to string and I can use it for other string comparisons? 有没有一种方法可以捕获print printHello代码的输出并将其用于比较,或者将printHello的类型转换为字符串,我可以将其用于其他字符串比较? Any help is appreciated. 任何帮助表示赞赏。

If you want to specifically compare to strings you could do it in two different ways. 如果要专门比较字符串,可以用两种不同的方法。 First is to define the __str__ method for your class: 首先是为您的类定义__str__方法:

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

Then you can compare to a string with: 然后,您可以将字符串与以下内容进行比较:

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

Or you could specifically use the __eq__ special function: 或者,您可以专门使用__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

then you can do the following: 那么您可以执行以下操作:

h = Hello()
h == "HelloWorld"

Either define str or repr in Hello class 在Hello类中定义strrepr

More information here - https://docs.python.org/2/reference/datamodel.html#object. 此处的更多信息-https: //docs.python.org/2/reference/datamodel.html#object。 str 力量

A special method __repr__ should be defined in your class for this purpose: 为此,应在您的类中定义一个特殊的方法__repr__:

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

    def __repr__(self):
        return "printHello"

I think you want: 我想你要:

string_value = printHello.__str__()

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

The __str__() method is used by print to make sense of class objects. print使用__str__()方法来理解类对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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