user2518
user2518

Reputation: 139

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.

Upvotes: 2

Views: 8685

Answers (4)

cts
cts

Reputation: 1820

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"

Upvotes: 4

schafle
schafle

Reputation: 613

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"

Upvotes: 1

Boaz Galil
Boaz Galil

Reputation: 72

Either define str or repr in Hello class

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

Upvotes: 1

Will
Will

Reputation: 4469

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.

Upvotes: 0

Related Questions