Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have an object output a default value

Tags:

python

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"
like image 413
BaguetteYeeter Avatar asked Mar 02 '23 13:03

BaguetteYeeter


1 Answers

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__?

like image 131
Ann Zen Avatar answered Mar 16 '23 04:03

Ann Zen