Loading...

Better way than pass the same argument among classes in Python


I have a question related to OOP but it should be implemented in Python.

I have a file user_inputs.py with all the user parameters.

In my main file, I have a function that is called first. This function is responsible to read all the user parameters and return a dictionary that will be used in the rest of the program.

My question is: what is the cleanest way to pass the user_parameters dictionary to all classes? I did it in 2 ways:

Method 1)

def read_user_parameters():
        # code to open and read all parameters etc.
        return user_parameters  # returns a dictionary with all the user parameters


Class A():
    def __init__(self, user_parameters):
        self.user_parameters = user_parameters


Class B():
    def __init__(self, user_parameters):
        self.user_parameters = user_parameters


user_parameters = read_user_parameters()
object_A = A(user_parameters)
object_B = B(user_parameters)

I don't like this way because I have dozens of classes that need to pass this argument. So I thought to create a parent class with the user parameters:

Method 2)

Class User_parameters():
    def  __init__(self, user_parameters):

    def read_user_parameters():
        # code to open and read all parameters etc.
        return user_parameters


Class A(User_parameters):
    __init__(self, user_parameters):
        super().__init__()
        # self.user_parameters comes from the parent class now


Class B(User_parameters):
    __init__(self, user_parameters):
        super().__init__()
        # self.user_parameters comes from the parent class now


object_A = A()
object_B = B()

I prefer method 2, however, when super() is initialized from Class A and Class B the function read_user_parameters() that reads the file will be called twice (multiply this by dozens of times). Is there a better solution than method 1 in which I call read_user_parameters() only once but doesn't need to pass the argument for all classes?

Thank you for your time.

- - Source

Answers

answered 1 week ago Devesh Kumar Singh #1

Why not just have a single UserParameters class and two objects of the same class (Also class nameds are supposed to be camel-cases, not snake-cased)

#Single class for user parameters
class UserParameters:
    def  __init__(self, user_parameters):
        self.user_parameters = user_parameters

    def read_user_parameters(self):
        # code to open and read all parameters etc.
        return self.user_parameters

#Two objects
object_A = UserParameters("<params>")
object_B = UserParameters("<params>")

comments powered by Disqus