3

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,998
  • 3
  • 16
  • 37
Mannix
  • 411
  • 10
  • 23

2 Answers2

5

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
  • 91,368
  • 6
  • 71
  • 106
  • 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
  • Not `__repr__` specifically, but the want for being able to call `c(...)` is for functional purposes. If your class has a primary function, it's nice to just be able to "call" the class... all the other methods become support for the primary function. For example scala has the `apply` method, in which `c.apply(arg)` and `c(arg)` is identical. – Stephen Dec 07 '22 at 23:08
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,661
  • 1
  • 12
  • 33