Python 函数使用常量。它们什么时候定义的?通常的做法是什么?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,函数内的每个语句在每次执行函数时都会运行。这是否会影响性能取决于语句的开销以及函数实际执行的频率。
要了解简单语句的成本,您可以使用 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.