0

Say, I have some MainClass which at some point in its methods has instantiation of an object of a OtherClass as an attribute of the MainClass.

mainobj = MainClass()
isinstance(mainobj.otherclassobj, OtherClass) == True

Now, I want to extend the OtherClass, and then use the MainClass with new extended class.

Do I have more convenient options, other than extending MainClass and redefining all of its methods which instantiate self.otherclassobj to do it from ExtendedOtherClass?

0

2 Answers 2

2

If you do not need OtherClass already, you can do something like

from other_class_module import ExtendedOtherClass as OtherClass

If you need both classes, or logic/method changed - you need to reimplement/extend MainClass.

Sign up to request clarification or add additional context in comments.

Comments

1

If you can change the implementation of MainClass slightly, you don't need to inherit from it. Just have something like

class MainClass:
    def __init__(self, ..., otherclass=OtherClass):
        self.otherclassobj = otherclass()
        ...
    ...

Then MainClass will by default use OtherClass, but you can pass in ExtendedOtherClass as a keyword argument.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.