Functions depending on other functions in Python

huangapple go评论60阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月6日 06:31:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定