1

Suppose you have a class in python. We'll call it C. And suppose you create an instance of it somewhere in your script, or in interactive mode: c=C()

Is is possible to have a "default" method in the class, such that when you reference the instance, that default method gets called?

class C(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def method0(self):
        return 0
    def method1(self):
        return 1
    def ...
        ...
    def default(self):
        return "Nothing to see here, move along"

And so on.

Now I create an instance of the class in interactive mode, and reference it:

>>> c=C(3,4)
>>> c
<__main__.C object at 0x6ffffe67a50>
>>> print(c)
<__main__.C object at 0x6ffffe67a50>
>>>

Is is possible to have a default method that gets called if you reference the object by itself, as shown below?

>>> c
'Nothing to see here, move along'
>>> print(c)
Nothing to see here, move along
>>>
SuperKogito
  • 2,825
  • 3
  • 14
  • 35
Mannix
  • 381
  • 7
  • 19

2 Answers2

4

What you're looking for is the __repr__ method, which returns the string representation of an instance of the class. You can override the method like this:

class C:
    def __repr__(self):
        return 'Nothing to see here, move along'

so that:

>>> c=C()
>>> c
Nothing to see here, move along
>>> print(c)
Nothing to see here, move along
>>>
blhsing
  • 77,832
  • 6
  • 59
  • 90
  • Nice. I figured python would have something like this. `__str__` and `__repr__` can only return strings? What if I want to return a list, or an array, or something else? – Mannix Apr 09 '19 at 23:41
  • The `__repr__` and the `__str__` methods can only return strings. What is your use case for it to return anything else? – blhsing Apr 09 '19 at 23:44
2

Any code that you want to run when an object starts should go in __init__() and if you want to alter the effect of print(instance) you can overwrite the __repr__() of the object. Together it would look like:

class C(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        print(self.__repr__())
    def __repr__(self):
        return 'nothing to see here'

c = C(3, 4)
print(c)

Outputting:

nothing to see here
nothing to see here

Where the first is printed when the class is made by calling print(self.__repr__()) and the next print comes from print(c)

Reedinationer
  • 5,388
  • 1
  • 11
  • 33