-1
class t2():
    def __init__(self, name, surname ):
        self.a = name
        self.b = surname
        return    

    def concatenate( what ):
        what.a = what.a + " " + what.b
        return

class t3( t2 ):
    def concatenate( self ):
        return self.a

xx = t3( "Lebron", "James" )
xx.concatenate()
print( xx.concatenate(), xx.a )

Bit confuse as to why this code gives the output of "Lebron Lebron" how does it know which function to use from which class? Thanks!

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
Yash Dwivedi
  • 71
  • 1
  • 5
  • 1
    T3 inherits from T2 and the concatenate method of T2 is overridden by T3. Python first looks for a method in the class and goes to the parent class if it doesn't find the method in the given class. – Arun Nov 19 '19 at 22:03
  • 1
    @YashDwivedi always post correctly formatted code. In any case, when you call the method, it checks the class first, then the parent class, then every class in the method resolution order for the method. This is called inheritance. – juanpa.arrivillaga Nov 19 '19 at 22:03
  • @YashDwivedi I meant T3. please check the edit. – Arun Nov 19 '19 at 22:06
  • For fun, try `t2.concatenate(xx)` and then `print(xx.a)`. Do you get what's happening there? – Fred Larson Nov 19 '19 at 22:08
  • Sorry, I ran the code and do not understand the result. The code print Lebron James however surely the concatenate inside of the class t3 should be run rather than the one inside of t2. I am assuming xx is defined as an instance of t3 rather than t2. – Yash Dwivedi Nov 19 '19 at 22:15

1 Answers1

0

Its because you xx is an instance of t3

When you call a method on xx python will look if the method is define in t3 class if not go look in the parent.

So he will use the concatenate method of t3 since its override in t3. (https://docs.python.org/3/tutorial/classes.html)

Best regard

TOTO
  • 307
  • 1
  • 6