python临时更改类默认值

时间:2018-02-22 14:00:46

标签: python default temporary

我想暂时更改类的默认值。我提出了一些想法:

class C(object):
    VALUE_DEFAULT = [1, 2, 3]
    def __init__(self, value=None):
        if value is None:
            value = self.VALUE_DEFAULT
        self._value = value

    @property
    def value(self):
        return self._value


print("Initial default:", C().value)

"""
1) Repetitious version that makes code unclear if multiple
instances should be instantiated or the default should not be used.
"""
print("Changed default manually:", C(value=[0, 2, 4]).value)

"""
2) dangerously hard coded version
"""
C.VALUE_DEFAULT = [0, 2, 4]
print("Changed default by changing the default constant:", C().value)
C.VALUE_DEFAULT = [1, 2, 3]


"""
3) possibly more pythonic version
still this version seems hacky
"""
from contextlib import contextmanager

@contextmanager
def tmp_default(cls, name, value):
    old_val = getattr(cls, name)
    setattr(cls, name, value)
    yield
    setattr(cls, name, old_val)

with tmp_default(C, "VALUE_DEFAULT", [0, 2, 4]):
    print("Changed default with contextmanager:", C().value)

print("Restored the default again:", C().value)

从上述可能性来看,我非常喜欢3)。任何进一步的想法或改进?

提前致谢

2 个答案:

答案 0 :(得分:2)

有一个可选的关键字参数是应该在Python中完成的方式。虽然,我想指出你的代码有问题。

class C(object):
    VALUE_DEFAULT = [1, 2, 3]
    def __init__(self, value=None):
        if value is None:
            value = self.VALUE_DEFAULT
        self._value = value

    @property
    def value(self):
        return self._value

c1 = C()
c2 = C()
c1.value [0] = 10
c2.value # [10, 2, 3]

由于您将相同的可变列表指定为默认值,因此更新c1.value更新C.VALUE_DEFAULT

以下是解决此问题的方法。

class C(object):
    def __init__(self, value=None):
        # create a new array everytime
        self._value = [1, 2, 3] if value is None else value

    @property
    def value(self):
        return self._value

每当您需要默认值以外的其他值时,请将其作为关键字value提供。

或者,如果您想解决可变性错误,但仍然使用其他解决方案,则需要copy

import copy

class C(object):
    VALUE_DEFAULT = [1, 2, 3]
    def __init__(self, value=None):
        if value is None:
            value = copy.copy(self.VALUE_DEFAULT)
        self._value = value

    @property
    def value(self):
        return self._value

答案 1 :(得分:2)

这是我的建议,涉及工厂。

def make_cfactory(argument):
    return lambda : C(argument.copy())

我想使用参数C来实例化一堆[1,2,3],但我不想继续输入[1,2,3]。我没有用C(...)实例化它们,而是使用工厂实例化它们。

cfac = make_cfactory([1,2,3])
c1 = cfac()
c2 = cfac()
c3 = cfac()
cfac = make_cfactory([100,12])
c4 = cfac()
c5 = cfac()
c6 = cfac()

c1c2c3 value [1,2,3]c4c5c6value [100,12]

如果您将其他参数传递给C初始化程序,则可以向make_cfactory和/或lambda函数添加参数。