我想暂时更改类的默认值。我想出了一些想法:
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()
c1
、c2
和 c3
的值
为[1,2,3]
。
c4
、c5
和 c6
的值
为[100,12]
。
如果将其他参数传递给 C
初始化程序,则可以将参数添加到 make_cfactory
和/或 lambda 函数。
关于python临时更改类默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48929299/