Question

I'm a newbie in writing OO program, and I cannot find any good solution of the problem I'm facing. May anyone please help?

I'm sourcing some modules which I cannot freely modify it, and I would like to add a method on a superclass so that I can call on instances of subclasses. So in my module:

import externalLib as myLib

class Superclass(myLib.Superclass):

    def myNewMethod(self):
        print(self.name)   # Print a member variable

def __main__():

    obj = myLib.Subclass(args)
    obj.myNewMethod()    # Expect prints the same member variable in subclass

Result: "Subclass" has no attribute or method named "myNewMethod".

  1. Extending all the subclass is not possible to me, as there are too many subclasses.

  2. I could solve the problem by defining the function under my module instead of the Superclass, but I just think that way is not like an OO-architecture.

Is there any better solution? Or any keywords or OO design concept can I refer to?

Thanks!

Was it helpful?

Solution

Yes, there is one keyword - "wrong". OO is model, where what you want to do should NOT be done.

If you have REALLY good reason for that, you can do it much simpler:

import externalLib as myLib

def myNewMethod(self):
    print(self.name)

myLib.Superclass.myNewMethod = myNewMethod

Why didn't your code work?

When you defined Superclass inheriting from myLib.Superclass, it stayed ONLY in this module. When you defined your Superclass, name "Superclass" was bind with your new class only in global scope, but old value didn't change, co Superclass in myLib/externalLib scope stayed the same. I can see how you got impression that it may work, if you worked with classic-OO languages like Java or C++.

Little known fact - Java/C++ OO model is not really object-oriented. It does such impression, but OOP model is REALLY implemented in Smalltalk.

OTHER TIPS

You are looking to monkeypatch the original class. Because methods are just attributes on a class, you can always add more:

import externalLib as myLib

def myNewMethod(self):
    print(self.name)

myLib.Superclas.myNewMethod = myNewMethod
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top