英文:
Functions depending on other functions in Python
问题
以下是代码的中文翻译:
def mean(x):
return(sum(x)/len(x))
def variance(x):
x_mean = mean(x)
return sum((x-x_mean)**2)/(len(x)-1)
def standard_deviation(x):
return math.sqrt(variance(x))
这些函数相互依赖,每个函数都依赖于前一个函数。在Python中,你可以考虑使用类来实现这些函数,以便更好地组织它们并将它们归为一组。另外,你也可以使用模块来封装这些函数,这样可以更好地组织和管理代码。选择哪种方式取决于你的项目需求和偏好。
英文:
def mean(x):
return(sum(x)/len(x))
def variance(x):
x_mean = mean(x)
return sum((x-x_mean)**2)/(len(x)-1)
def standard_deviation(x):
return math.sqrt(variance(x))
The functions above build on each other. They depend on the previous function. What is a good way to implement this in Python? Should I use a class which has these functions? Are there other options?
答案1
得分: 3
因为它们具有广泛的适用性,所以保持它们原样。
程序的许多部分可能需要计算这些统计数据,不用从类中获取它们会节省冗余。此外,这些函数实际上不需要任何类存储的数据:它们只是类的静态方法。(在过去,我们通常称之为“函数”!)
如果它们需要存储内部信息以正确工作,那是将它们放入类的一个很好的理由。
在这种情况下的优势在于更容易让程序员知道正在共享哪些信息。此外,您可能希望创建两个或多个具有不同共享数据集的实例。但在这里并非如此。
英文:
Because they are widely applicable, keep them as they are
Many parts of a program may need to calculate these statistics, and it will save wordiness to not have to get them out of a class. Moreover, the functions actually don't need any class-stored data: they would simply be static methods of a class. (Which in the old days, we would have simply called "functions"!)
If they needed to store internal information to work correctly, that is a good reason to put them into a class
The advantage in that case is that it is more obvious to the programmer what information is being shared. Moreover, you might want to create two or more instances that had different sets of shared data. That is not the case here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论