简体   繁体   中英

How to convert an instance into String type in python?

say class instance is printHello for class Hello
Now when I execute below code
print printHello
The output is "HelloPrinted"
Now I want to compare the printHello with a string type and cannot achieve it because printHello is of type instance. 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? 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:

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:

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

More information here - https://docs.python.org/2/reference/datamodel.html#object. str

A special method __repr__ should be defined in your class for this purpose:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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