4

I have a class called myClass.

class myClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b

I have a variable which is an instance of myClass

myObject = myClass(5, 3)

How do I have it so that when I call myObject, it returns a set value instead of <__main__.myClass object at 0x100816580>.

For example,

>>> myObject
"some value"

1 Answers1

7

You can use the __repr__() dunder method:

class myClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return 'some string'

myObject = myClass(5, 3)
print(myObject)

Output:

some string

The __str__() dunder method would work too. See What is the difference between __str__ and __repr__?

Red
  • 26,798
  • 7
  • 36
  • 58