Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading