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.
4 Answers
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"
Comments
Either define str or repr in Hello class
More information here - https://docs.python.org/2/reference/datamodel.html#object.str
Comments
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"
1 Comment
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.
1 Comment
user2518
I got the below error >> AttributeError: Hello instance has no attribute 'str'
isinstance(printHello, Hello).print printHelloresults in"HelloPrinted"? DoesHellohave a__str__or__repr__method? You can get the name of the class withprintHello.__class__.__name__, is that what you want?