0

Code example:

>>> class Snake:
        pass

and then I do this

>>> snake = Snake()
>>> print(snake)
<__main__.Snake object at 0x7f315c573550>

How can I test what this returns?

if snake == "<__main__.Snake object at 0x7f315c573550>":
    print("it worked")

the if statement does not work. how can I test what snake is equal to in an if statement? thanks.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ohgodmanyo
  • 19
  • 3

2 Answers2

3

From the docs:

By default, object implements __eq__() by using is

So, if snake == snake, but that's a tautology.

I think what you actually want to do is check if snake is a Snake instance:

if isinstance(snake, Snake):
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

print displays the string representation of the object, not the object itself. In fact, the object itself is just a bunch of bits in memory, so what should it look like? In your case, you can get the same string representation and compare.

str(snake) == "<__main__.Snake object at 0x7f315c573550>":
    print("it worked")

Since the number at the end varies each time you create a Snake object, you could use a regex to match part of it while leaving details of that hex number to chance.

import re
if re.match(r"<__main__\.Snake object at 0x[\da-f]+>", str(snake)):
    print("it worked")
tdelaney
  • 73,364
  • 6
  • 83
  • 116