poobear
poobear

Reputation: 73

how do i pass optional parameter to the __init__ function in python class

I have a class that takes 3 parameters(2 compulsory and 1 optional). This is the part of my code:

def __init__(self, user, url, env=None):
    """init method for the class."""
    self.user = user
    self.url = url
    if env is None:
        self.env = ""
    else:
        self.env = env

def check_file(self):
    # get the env value from a dictionary
    if self.env == "test":
        self.address = value['key1']
    else:
        self.address = value['key2']

The address variable has 2 values, one for production env and one for test env. If this env variable is passed as p then the value of self.address should be production url address and if the env value is t then the self.address shpuld be test url address , but if the env value is not passed then the self.address value should be the key3 value from the dictionary value. These production url address and test url address are the key1 and key2 of the dictionary value

I came up with this code, but this seems to be not working.

Upvotes: 1

Views: 2967

Answers (1)

Edward Aung
Edward Aung

Reputation: 3522

Try this:

def __init__(self, user, url, env=None):
    """init method for the class."""
    self.user = user
    self.url = url
    if env is None:
        self.env = ""
    else:
        self.env = env

def check_file(self):
    # get the env value from a dictionary
    if self.env: # if not an empty string
        if self.env == "test":
            self.address = value['key1']
        else:
            self.address = value['key2']
    else:
        self.address = value['key3']

Upvotes: 3

Related Questions