Skip to content Skip to sidebar Skip to footer

How To Access A Method Inside A Class?

Environment: Python 2.7 (Might be related). for example, I want to call class original __repr__ method depending on if an attribute on instance has been set. class A(object): #

Solution 1:

I think you looking for,

super().__repr__()


classA:# original_repr = ?__repr__def__init__(self, switch):
        self.switch = switch

    def__repr__(self):
        returnsuper().__repr__()

Solution 2:

def__repr__(self):
        ifself.switch:return"Hello"returnsuper().__repr__()

Solution 3:

You can fallback on the __repr__ method of the super-class via super().__repr__(). I will show an example below by subclassing a new class.

So if we have a parent class B as follows, with it's own __repr__ defined

classB:def__repr__(self):

        return'This is repr of B'

And then we have a child class A as before, which inherits from B, it can fall back to __repr__ of B as follows

class A(B):

    def __init__(self, switch):
        super().__init__()
        self.switch = switch

    def __repr__(self):
        #If switch is True, return repr of A
        ifself.switch:
            return'This is repr of A'
        #Else return repr of B by calling superelse:
            returnsuper().__repr__()

You can test out this by doing

print(A(True))
print(A(False))

As expected, the first case will trigger the __repr__ of A, and the second case will trigger the __repr__ of B.

This isrepr of A
This isrepr of B

If A is just a normal class which inherits from object, the code will change to

classA:

    def __init__(self, switch):
        super().__init__()
        self.switch = switch

    def __repr__(self):
        #If switch is True, return repr of A
        if self.switch:
            return'This is repr of A'
        #Else return repr of superclass by calling superelse:
            returnsuper().__repr__()

And the output will change to

print(A(True))
#This is repr of Aprint(A(False))
#<__main__.A object at 0x103075908>

Post a Comment for "How To Access A Method Inside A Class?"