英文:
How to calcutate several functions in class without reiteration
问题
需要计算一些变量,这些变量可以被其他变量使用:
class Variables:
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
def var1(self):
return self._param1 + 'foo'
def var2(self):
return var1() + 'bar'
....
def var9(self):
return var2() + var8()
def var10(self):
return var3() + var9()
问题是,在模块外部调用它们时,中间函数var1..var9多次计算。我尝试在__init__
中计算它们:
def var1(self):
return self._param1 + 'foo'
def var2(self):
return self._var1 + 'bar'
....
def var9(self):
return self._var2 + self._var8
def var10(self):
return self._var3 + self._var9
class Variables:
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
self._var1 = var1(self)
self._var2 = var2(self)
....
self._var9 = var9(self)
self._var10 = var10(self)
但是我的直觉告诉我,这个决定很糟糕:类内外的self是“不同的”。出于某些原因,我需要10个单独的函数,不能将它们合并为一个大函数。最佳方法是如何计算和存储它们?
英文:
I need to calculate some variables, which can be used by other variables:
class Variables:
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
def var1(self):
return self._param1 + 'foo'
def var2(self):
return var1() + 'bar'
....
def var9(self):
return var2() + var8()
def var10(self):
return var3() + var9()
Problem is that intermediate functions var1..var9 are calculating multiple times when I call them outside module. I tried to calculate them in __init__
:
def var1(self):
return self._param1 + 'foo'
def var2(self):
return self._var1 + 'bar'
....
def var9(self):
return self._var2 + self._var8
def var10(self):
return self._var3 + self._var9
class Variables:
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
self._var1 = var1(self)
self._var2 = var2(self)
....
self._var9 = var9(self)
self._var10 = var10(self)
But my intuition tells me that this decision is terrible: self-s inside and outside class are "different".
For some reasons I need 10 separate functions and cant combine them in one big function. What is the best way to calculate and store them?
答案1
得分: 1
class Variables:
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
self._var1 = self._generate_var1()
... 类似地处理 var2 到 var10
def _generate_var1(self):
var1 = self._param1 + 'foo'
return var1
def var1(self):
return self._var1
... 类似地处理 var2 到 var10
英文:
class Variables:
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
self._var1 = self._generate_var1()
... similarly for var2 through var10
def _generate_var1(self):
var1 = self._param1 + 'foo'
return var1
def var1(self):
return self._var1
... similarly for var2 through var10
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论