我如何将可选参数传递给python类中的__init__函数

时间:2019-03-19 05:25:28

标签: python

我有一个带有3个参数的类(2个必选和1个可选)。 这是我的代码的一部分:

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']

address变量具有2个值,一个用于生产环境,一个用于测试环境。如果将此env变量作为p传递,则self.address的值应为生产URL地址,如果env的值为t,则{{1 }}应该是测试url地址,但是如果未传递self.address值,则env值应该是字典self.address中的key3值。这些生产URL地址和测试URL地址是字典value的{​​{1}}和key1

我想出了这段代码,但这似乎不起作用。

1 个答案:

答案 0 :(得分:1)

尝试一下:

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']