Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a default method for a class in python? [duplicate]

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
>>>
like image 981
Mannix Avatar asked Oct 29 '25 07:10

Mannix


1 Answers

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
>>>
like image 120
blhsing Avatar answered Oct 31 '25 12:10

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!