【发布时间】:2018-02-22 14:00:45
【问题描述】:
我想临时更改一个类的默认值。我想出了一些想法:
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)。有什么进一步的想法或改进吗?
提前致谢
【问题讨论】:
-
为什么不简单地在创建这个类的实例时设置你想要的值呢?
-
看起来这对工厂来说更有意义。
-
@Haleemur 我需要创建大量实例。所以变体1非常重复。
-
@khelwood :好主意,不过,我需要多次更改默认值。因此,我最终会创建 100 家工厂,或者再次通过一个论点,这将使创建工厂变得多余甚至更加混乱。
-
拥有数百家工厂不会花费您任何成本。