Home > Enterprise >  override a method of a class with an method from another class
override a method of a class with an method from another class

Time:10-13

I have following code:

    class SomeClass:
        def __init__(self) -> None:
            pass
    
        def some_class_function(self, par):
            print(par)
    
    class SomeOtherClass:
        def __init__(self) -> None:
            pass
    
        def some_other_class_function(self, par):
            print(par 1)
    
    if __name__ == "__main__":
        sc = SomeClass()
        sc.some_class_function = SomeOtherClass.some_other_class_function
        sc.some_class_function(1)

When I execute the code I get

TypeError: some_other_class_function() missing 1 required positional argument: 'par'

How can I override the method of the first class with the method of the second class properly?

CodePudding user response:

You need to initialize the class to call its method.

sc = SomeClass()
sco = SomeOtherClass() # initialize the second call to call it's method
sc.some_class_function = sco.some_other_class_function
sc.some_class_function(1)

CodePudding user response:

As you have noted in the comments, you are interested in adding method that will use sc as the "self" instance.

To that end, see this post. To summarize, you can either add a function to the class definition (affecting future instances of the same class), or bind the function to the particular instance.

As an example, consider the following class and function.

class Test():
    def __init__(self):
        self.phrase = "hello world"
    def func(self):
        print("this is the old method")

def test_func(self):
    print(self.phrase)

For the first approach, we could do the following

test = Test()
Test.func = test_func
test.func()

Note that future instances of Test will have this function as an attribute. For example, running Test().func() will still result in the same output, even though the method is being used on a new class instance.

For the second, we could do the following.

import types

test = Test()
test.func = types.MethodType(test_func, test)
test.func()

In this case, running the line Test().func() will result in the output "this is the old method" because func has not been overwritten for new instances.

  • Related