vendredi 18 mars 2022

Refactor the python design patterns

I have a class called resources and I have defined one method called get_connect. I want to use the data of which get_connect returns to the other classes. I need at least three classes and I use the data of get_connect and I have to parse that data. To implement this I have written the code below


class resources:
    @staticmethod
    def get_connect():       
        
        return 1 + 2


class Source1(resources):
    def __init__(self):
        self.response = resources.get_connect()

    def get__details1(self):
        print(self.response)

class Source2(resources):
    def __init__(self):
        self.response = resources.get_connect()
    def get_details2(self):
        print(self.response)

class Source3(resources):
    def __init__(self):
        self.response = resources.get_connect()
    def get__detail3(self):
        print(self.response)

source1 = Source1()
source2 = Source2()
source3 = Source3()
source1.get__details1()
source2.get_details2()
source3.get__detail3()

But the problem with the code is for every class in init method I am calling the get_connect method. I don't want to repeat the code. I need help for avoiding redundancy which I have asked below

  1. Is there any way I can call get_connect in one place and use it for other classes maybe a decorator or anything? if yes how can I?
  2. While creating objects also I am calling each class and calling each method every time. is there a way to use any design pattern here?

If anyone helps me with these oops concepts it will be useful.

Aucun commentaire:

Enregistrer un commentaire