Which type of variable should be initialized inside the class for different purpose

Viewed 47

I have multiple variables which want to be initialized,

trading_symbol = "TSLA" # won't change in the future
trading_period = read_config_json("trading_period") # will changed only inside config.json
count = 0 # will be changed inside the class frequently

Where trading_symbol, trading_period, and count should be placed in the Trading class is the best practice in Python?

# define as a global variable
class Trading:
    # define as a class variable
    def __init__:
        # define as an instance variable
    def run():
        # running some trading logic here

if __name__ == "__main__":
    # define as a global variable but won't be called by  importing
    trading = Trading()
    trading.run()
2 Answers

I'd say instance variables are the best practice for this design.

class Trading:
    def __init__(self, symbol, period, count):
        self.symbol = symbol
        self.period = period
        self.count = count

    def run(self):
        ...


if __name__ == "__main__":
    trading = Trading(symbol="TSLA", 
                      period=read_config_json("trading_period"),
                      count=0)
    trading.run()

Like this you will be able to get these variables in the run function to do whatever you want in the class itself.

Is this class a singleton? If so, my preference in python would be to use global variables, use functions to manipulate them, and put the whole kit and caboodle into its own file. If you're quite set on using a singleton, then use instance variables wherever you can (but yuck). If it's not a singleton, it's usually quite clear what should be an instance variable and what should be a class variable: use instance variables when each instance may require its own copy of the variable (I.E the variable may have different values between instances), and use class variables for all else. To choose between class variables and globals, think about which classes will use the variable. If multiple, then maybe a global, unless it holds a mutable value, then it should probably be in the class that controls and changes it.

Related