Python 函数使用常量。它们什么时候定义的?通常的做法是什么?

发布于 2025-01-17 06:15:56 字数 444 浏览 2 评论 0原文

Python 函数定义了一些“常量”变量,以使其更具可读性和健壮性。我们来写一个例子。

def definite_calculus(x, y):
    """This is a very specific function."""
    coeff1 = 3.14**2/16
    coeff2 = 2.72//27
    return coeff1*x**2 + coeff2*x + 6*y

我担心如果在函数内声明常量,代码会多次执行此声明。如果常数像字典一样很重怎么办?那工作量太大了。

问题 1. 何时在函数内声明“常量”变量?每次运行还是一次?如果Python创建这些变量一次,那么当“编译”函数时,Python如何知道这些是“常量”而不是将被重新分配或覆盖的变量?

问题 2. 通常的 Pythonic 约定是什么?使用大写还是不使用大写?里面声明还是不声明?

A Python function defines some "constant" variables to be more readable and robust. Let's write one example.

def definite_calculus(x, y):
    """This is a very specific function."""
    coeff1 = 3.14**2/16
    coeff2 = 2.72//27
    return coeff1*x**2 + coeff2*x + 6*y

I am worried that if declare constants inside a function, the code does this declaration many times. What if the constant is very heavy like a dictionary? That would be too much work.

Question 1. When are "constant" variables declared inside a functions? Every time you run it or once? If Python creates those variables once, when "compiling" the function, how does Python know that those are "constants" and not variables that will be reassigned or overwritten?

Question 2. What is the usual Pythonic convention? Using uppercase or not? Declaring inside or not?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笛声青案梦长安 2025-01-24 06:15:56

事实上,函数内的每个语句在每次执行函数时都会运行。这是否会影响性能取决于语句的开销以及函数实际执行的频率。

要了解简单语句的成本,您可以使用 python 标准库

如果不是太贵,我建议在函数内声明变量(如果它们仅在函数内有意义)。

indeed each statement inside a function runs every time the function is executed. Whether this affects performance depends on how expensive the statement is and how often the function is actually executed.

To find out how expensive a simple statement is you can use the python standard lib timeit.

If not too expensive, I would advise declaring variables inside the function if they are only meaningful within the function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文