python临时更改类默认值

标签 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)。还有进一步的想法或改进吗?

提前致谢

最佳答案

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

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

我想用参数 [1,2,3] 实例化一堆 C,但我不想继续输入 [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[1,2,3]
c4c5c6[100,12]

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

关于python临时更改类默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48929299/

相关文章:

c++ - 什么时候计算右值?

python - 有没有办法用mypy覆盖python中继承的类属性类型?

python - 指定默认参数的惯用方式,其存在/不存在很重要

Java默认构造函数没有初始化

C++ 模板,vector.size 用于默认参数定义

c++ - c++中堆栈分配数据的生命周期

python - 替换列表列表中的值

python - Windows 中没有名为 'tkinter' (Python3.8) 的模块

select - Ember.选择默认选项

pointers - Go中的临时地址?