Search code examples
pythonoverridingclass-methodinstance-methods

In Python, why does a class method override an instance method?


See code below:

class MyClass:

    # instance method.
    def printline(self):
        print('This is an instance method!')

    @classmethod
    def printline(cls):
        print('This is a class method!')


# class MyClass ends.

obj = MyClass()
obj.printline()

Output:

This is a class method!

So why is the class method overriding the instance method? Ignoring the fact that we can simply change the name of one of the method, how do access the instance method in the above code?


Solution

  • The latest definition of the function will mask the previous one. If the instance method was defined like the 2nd example below, you would be calling it:

        In [1]: class MyClass:
           ...:
           ...:     # instance method.
           ...:     def printline(self):
           ...:         print('This is an instance method!')
           ...:
           ...:     @classmethod
           ...:     def printline(cls):
           ...:         print('This is a class method!')
           ...:
    
        In [2]: m =  MyClass()
        
        In [3]: m.printline()
        This is a class method!
        
        In [4]: class MyClass1:
           ...:
           ...:     @classmethod
           ...:     def printline(cls):
           ...:         print('This is a class method!')
           ...:
           ...:     # instance method.
           ...:     def printline(self):
           ...:         print('This is an instance method!')
    
        In [5]: m1 = MyClass1()
        
        In [6]: m1.printline()
        This is an instance method!