Can you override a function from a class outside of a class in Python

Question:

Can you override a function from a class, like:

class A:
    def func():
        print("Out of A")


classA = A

# Is something like this possible
def classA.func():
    print("Overrided!")

Wanted Output:
Overrided

I googled "python override function", "python override function from class" and so on but couldnt find anything that fits. I found just how to override the parent function.

Asked By: nottrue

||

Answers:

You most likely shouldn’t do this. If you want to change a single part of some class, make a new class that inherits from it and reimplement the parts you want changed:

class A:
    @staticmethod
    def func():
        print("Out of A")

classA = A

class B(A):
    @staticmethod
    def func():
        print("Overridden!")

A.func()
B.func()
Answered By: matszwecja
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.