0

I'm looking to implement the Strategy Pattern and was on my way to do as the answer in Stack Strat Pattern. But realised that I would be unable to copy it right of the bat. What I want to do is implement the pattern but also make sure that my executeReplacement functions inherit from the base class.

class DB():

    def __init__(self, league, season, func=None):
        self.db_user = os.environ.get('DB_user')
        self.db_pass = os.environ.get('DB_pass')
        self.MONGODB_URL = f'mongodb+srv://{db_user}:{db_pass}@database-mbqxj.mongodb.net/test?retryWrites=true&w=majority'
        self.client = MongoClient(MONGODB_URL)
        self.DATABASE = client["Database"]
        self.league = league
        self.season = season
        self.pool = multiprocessing.cpu_count()
        if func:
            self.execute = func

        def execute(self):
            print("No execution specified")

def executeReplacement1():
    """Should inherit the the properties of the base class
    since it's dependant on it's properties (Connect to Database etc.)"""
    print("Push some data to DATABASE")


def executeReplacement2():
    """Should inherit the the properties of the base class
    since it's dependant on it's properties (Connect to Database etc.)"""
    print("Push some other data to DATABASE")

How would one build the Strategy Pattern so that the replacement functions inherit the properties of the base class? Or is this perhaps not the optimal approach?

The goal is to parse arguments from stdin like:

`db --push EN_PR 2019 player``

Which will create an instance of the class DB in where the methods are bound to push where push is a functions that uploads data to the database.

MisterButter
  • 608
  • 5
  • 19

1 Answers1

1

The function should be defined to take a DB instance as an argument, then DB.execute can pass self when calling it.

class DB():

    def __init__(self, league, season, func=None):
        self.db_user = os.environ.get('DB_user')
        self.db_pass = os.environ.get('DB_pass')
        self.MONGODB_URL = f'mongodb+srv://{db_user}:{db_pass}@database-mbqxj.mongodb.net/test?retryWrites=true&w=majority'
        self.client = MongoClient(MONGODB_URL)
        self.DATABASE = client["Database"]
        self.league = league
        self.season = season
        self.pool = multiprocessing.cpu_count()
        self.func = func

        def execute(self):
            if self.func is not None:
                return self.func(self)

def executeReplacement1(db):
    print("Push some data to DATABASE")


def executeReplacement2(db):
    print("Push some other data to DATABASE")
chepner
  • 389,128
  • 51
  • 403
  • 529