我正在开发一个应用程序,其中变量初始化为默认值。
用户可以随时更改这些值。用户应该可以随时将部分或全部变量重置为默认值。
最好的解决方法是什么?
这将是一个解决方案,但我觉得它不是最理想的。你能告诉我我的感觉是否正确以及如何做得更好?
A_DEFAULT = "A_def"
B_DEFAULT = "B_def"
C_DEFAULT = "C_def"
class BusinessLogic_1(object):
def __init__(self):
self.setVariablesToDefault()
def setVariablesToDefault(self, variableNames=None):
# pass None to set all Variables to default
variableNames = variableNames or ["A","B","C"]
if "A" in variableNames:
self.A = A_DEFAULT
if "B" in variableNames:
self.B = B_DEFAULT
if "C" in variableNames:
self.C = C_DEFAULT
def printVariables(self):
print "A: %s, B: %s, C: %s" % (self.A, self.B, self.C)
if __name__ == "__main__":
print "0: Initialize"
businessLogic_1 = BusinessLogic_1()
businessLogic_1.printVariables()
print "Change A,B,C and then reset A,C"
businessLogic_1.A = "A_new"
businessLogic_1.B = "B_new"
businessLogic_1.C = "C_new"
businessLogic_1.printVariables()
答案 0 :(得分:1)
这可能是一个解决方案。 这是一种将变量名称作为字符串传递然后通过这些名称访问它们的方法。 对象可以同时具有多个名称,但名称始终指向单个对象(在给定的时间点)。
class classWithVariablesThatHaveDefaultValues(object):
def __init__(self, some, example, variables, defaultValuesDict):
self.some = some
self.example = example
self.variables = variables
self.dictionaryWithDefaultValues = defaultValuesDict
def resetValues(self, *listOfVariables):
for variable in listOfVariables:
for key in self.dictionaryWithDefaultValues:
if key == variable:
vars(self)[key] = self.dictionaryWithDefaultValues[key]
if __name__ == "__main__":
defaultValuesDict = {"some":4, "example":5, "variables":6}
exampleObject = classWithVariablesThatHaveDefaultValues(1, 2, 3, defaultValuesDict)
exampleObject.some = 15
print exampleObject.some, exampleObject.example, exampleObject.variables
exampleObject.resetValues("example", "some")
print exampleObject.some, exampleObject.example, exampleObject.variables
输出是:
15 2 3
4 5 3
答案 1 :(得分:0)
您可以通过与decimal.localcontext()
的工作方式非常相似的方式实现它,但根据您的使用情况,这可能不合适。这将允许您操作并调用反映更新值的原始对象上的任何方法,并在with
块的末尾,将它们重置为输入时的值。
from contextlib import contextmanager
class A(object):
def __init__(self):
self.a = 3
self.b = 5
def display(self):
return self.a, self.b
a = A()
@contextmanager
def mycontext(obj):
old_a = obj.a
old_b = obj.b
yield obj
obj.a = old_a
obj.b = old_b
print 'before:', a.display()
with mycontext(a) as obj:
print 'entered:', a.display()
a.a = 3
a.b = 7
print 'changed:', a.display()
print 'hopefully original', a.display()
before: (3, 5)
entered: (3, 5)
changed: (3, 7)
hopefully original (3, 5)