Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override __repr__() in Python3?

Tags:

python

class

I'm trying to sort out how to get a python object to return a default value by simply calling the object itself. Basically, this is equivalent to a class 'default member' common to other languages (I remember using it way back in my VB days).

For example, suppose I create a SuperTuple() class that extends the basic Python tuple. If I call the object with no parameters, I want it to return the Python tuple, not a string representation (as __repr__()) does.

That is if my basic class looks like:

class SuperTuple():

    _tuple = ()

    def __init__(self, tuple):
        _tuple = tuple

I want the following behavior:

>>> a = SuperTuple((1,2,3))
>>> a._tuple
(1, 2, 3)
>>> a
(1, 2, 3)

I suspect there isn't a way to do it in Python without arbitrarily creating some 'default' class member that needs to be explicitly called, which somewhat defeats the purpose.

The advantage, of course, would be to be able to use it in other operations without having to mess with operator overloading and other related issues:

>>> a = Supertuple(1, 2, 3)
>>> b = a + (4, 5, 6)
>>> b
(1, 2, 3, 4, 5, 6)
>>> type(a)
<class 'SuperTuple'>
>>> type(b)
<class 'tuple'>
like image 806
Joel Graff Avatar asked Jul 09 '26 03:07

Joel Graff


1 Answers

Python has no "default attribute", as VB or other languages may have.

It looks like you want to make SuperTuple a descendant of tuple, so that the object itself is just an extension of tuple:

class SuperTuple(tuple):
    pass

It will inherit all behaviour from tuple, including starting it with a default value:

>>> t = SuperTuple((1, 2, 3))
>>> t
(1, 2, 3)
>>> type(t)
__main__.SuperTuple

Edit: You can override other magic methods to include the behaviour you want, for example:

class SuperTuple(tuple):

    def __add__(self, other):
        return SuperTuple(tuple(self) + other)

>>> t = SuperTuple((1, 2, 3))
>>> t2 = t + (4, 5, 6)
>>> t2
(1, 2, 3, 4, 5, 6)
>>> type(t2)
__main__.SuperTuple
like image 137
augustomen Avatar answered Jul 11 '26 17:07

augustomen