2

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.

3
  • 1
    This is very difficult to follow. Please add code for context. Commented Mar 6, 2016 at 4:48
  • What is your goal for comparing? If you want to see if the object is a certain type, use isinstance(printHello, Hello). Commented Mar 6, 2016 at 5:05
  • How in the world did a class named 'Hello' end up so that print printHello results in "HelloPrinted"? Does Hello have a __str__ or __repr__ method? You can get the name of the class with printHello.__class__.__name__, is that what you want? Commented Mar 6, 2016 at 5:09

4 Answers 4

4

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"
Sign up to request clarification or add additional context in comments.

Comments

1

Either define str or repr in Hello class

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

Comments

1

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

0

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

I got the below error >> AttributeError: Hello instance has no attribute 'str'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.