Home > Net >  Can you override a function from a class outside of a class in Python
Can you override a function from a class outside of a class in Python

Time:12-01

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.

CodePudding user response:

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()
  • Related