Home > Back-end >  Conventional way of initializing class variables via methods (class methods or methods outside class
Conventional way of initializing class variables via methods (class methods or methods outside class

Time:10-15

I have 3 different config files from which I would want to initialize different class variables for different major functions

Q1. What is the more conventional way of initializing class variables via methods (class methods or methods outside class)

Q2. How to initialize class variables via class methods

config.py

    class CONFIG:
        x_config = 'x_config.json'
        y_config = 'y_config.json'
        z_config = 'z_config.json'

CodePudding user response:

You can use a dictionary to set the config values,

class CONFIG:
    
    # Class initialisation happens here
    def __init__(self, config_value):
        default_config = 'x_config.json' # Set your default config file
        config_dict = {'x_config': 'x_config.json',
                        'y_config': 'y_config.json',
                        'z_config': 'z_config.json'}
        self.config_file = config_dict.get(config_value, default_config)

# You can pass the default config value to the class
config = CONFIG('y_config')
print(config.config_file)

Output:

'y_config.json'

Q1. What is the more conventional way of initializing class variables via methods (class methods or methods outside class)

ANS: Via init method __init__

Q2. How to initialize class variables via class methods

ANS: It's not a best practice to initialize from its methods. You can rewrite the class attribute from the class methods.

self.config_file = 'z_config.json'

This can call from the class methods.

CodePudding user response:

Option 1

The most conventional way would be to initialize them in the __init__ method of the class.

Option 2

You can initialize class variables in class methods by using the self keyword. For example:

class MyClass:
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def class_method(self):
        self.var1 = 3
        self.var2 = 4
  • Related