如何在仅带有** kwargs参数的构造函数中正确使用空列表作为默认参数

I'm aware that using an empty list (or any other mutable type) as a default parameter is not a good idea, as it is described here: Why is the empty dictionary a dangerous default value in Python?.

I'm writing a class that is going to have a rather large amount of keyword arguments and that's why I have switched to **kwargs arguments (Class with too many parameters: better design strategy?).

我的课看起来像这样:

class Scale:
    fifth_tuning = {"perfect":3/2, "meantone":5**(1/4), "equal":(2**7)**(1/12)}

    def __init__(self, **kwargs):
        scale_defaults = {
            "stack_span": 7,
            "stack_interval": self.fifth_tuning["perfect"],
            "base_frequency": 261.626,
            "base_position": 0,
            "omit_positions": list()
        }

        for (key, default_value) in scale_defaults.items():
            setattr(self, "_"+key, kwargs.get(key, default_value))

        self._freqarray = []

        self._generate_freqarray()

现在,我不确定是否要通过使用默认字典并在其中定义一个新的空列表来避免使用可变的默认参数的危险,或者这种方法是否可能存在潜在的危险后果。有人可以确认我在做什么吗?如果不是,那是为什么呢?

评论