-1

I have a parent class with a lot of methods. I want some of them inherited in all of the child classes. Some of the methods I only want in certain classes. Can I somehow select which methods to inherit. I know I could override them in the child class, but I would prefer a positive approach of adding what you want instead of overriding the ones you don't want.

I am using the backtrader library.

class BaseStrategy(bt.Strategy):

    def notify_cashvalue(self, cash, value):
        if value < self.starting_cash * self.terminate_threshold:
            self.log(f'Stopping strategy at due drop below {self.terminate_threshold * 100}% of initial cash.')
            self.cerebro.runstop()

This is the class I want inherit from. As you see parent class is a child class to the library base, but this class implements empty methods.

Methods like notify_cashvalue are always called when this class is used. In my example notify_cashvalue has some attributes that will not be defined in all the child classes, so there would an error as notify_cashvalue is allways called, as are several other functions, which I want to selectively inherit.

Borut Flis
  • 15,715
  • 30
  • 92
  • 119

1 Answers1

0

I found here Is it possible to do partial inheritance with Python? that you can select the methods you want in this way:

class Class0():
    def hello():
        return "Hello"
    def bye():
        pass
    def nice():
        pass
class Class1():
    Hello = Class0.hello
Jock
  • 388
  • 2
  • 12
  • Welcome to Stack Overflow. Questions like this that are duplicates of an existing question should be closed and not answered. – Karl Knechtel Jun 14 '22 at 08:26