繁体   English   中英

在 function 定义中使用与在 python 中调用 function 时使用的变量相同的名称是否错误

[英]is it wrong to use same names for variables inside the function definition as thevariables used when calling a function in python

基本上就是标题所说的。

说我有一个 function 定义

def add_one (num1):
    numOut = num1 +1
    return numOut

我调用 function 如下

num1 = 11
numOut = add_one (num1)

这被认为是不好的做法,因为我们用相同的名称命名两个不同的对象,还是增加可读性的好做法? 或者它是我完全错过的东西?

(还检查了使用相同名称将变量传递给 function以及在 function 中使用一些与其同名的变量 function 是否正常,但他们不参考 python?

首先,让我们谈谈范围:

在 python 和许多其他语言变量中存在于其 scope 中。 这意味着如果您在 scope 中创建一个变量,那么当您离开该 scope 时,它将停止存在。

外部 scope 上的变量也可以在内部 scope 中访问,但是如果您对该变量进行了某些操作,那么它将被重新声明为该 scope 中的局部变量。 这意味着该变量将不同于外部 scope 上的变量。

如果您问我,我认为使用与您的函数的 arguments 相同的名称不是一个坏习惯。 事实上,我会称之为不好的做法,试图避免这种情况,因为你最终会试图为具有相同含义的不同变量找出新名称。

您应该避免的是使用不在本地 scope 上的变量(无论您使用什么语言)。

尽量不要担心。 有时,参数变量与函数的参数具有相同的名称是有意义的,但您永远不想强制执行。 您主要关心的是定义 function 的代码应该是有意义的,无论它如何被调用。

Remember that you might want to call a function passing some expression other than a plain variable, or that you might want to call the same function more than once in the same scope with different arguments. 尝试匹配您调用的 function 的参数名称只有在您想不出更好的变量名称时才有意义。

这样做时,总是需要考虑以下事项:

  • 我是否覆盖了我可能需要的变量的名称?
  • 我是否覆盖了 function 的名称?
  • 在函数的上下文中,变量是否已经存在?

但是,在 python 中,最后一点无关紧要,因为无法在函数的 scope 内访问外部变量(不包括全局变量)。

在以下示例中,function 的名称被覆盖(这是错误的):

def myFunc (a, b):
    myFunc = 2
    if a > 2 and a > b:
        return a
    return b

在下一个示例中,function 的上下文 / scope 更改了您在非 python 的语言中可以访问的变量:

x = 3

def myFunc (a, b):
    if a + x > b + x:    # in some languages this would work, but in python this is an error because x is not defined in the function.
        x = 5            # here x == 5, because we have redefined it. x is still 3 outside of our function though.
        return a + x
    return b

在第二个示例中,在设置值之前使用变量的值被认为是不好的做法,但是在 python 中您不必担心,因为这是不可能的。

我完全错过的东西

python中函数的重要特征是它们的可重用性,想象一下改变需求会迫使你使用你的 function

def add_one (num1):
    numOut = num1 +1
    return numOut

不是一个,而是两个不同的变量,你可能会以

num1 = 11
num2 = 15
numOut = add_one (num1)
numOut2 = add_one (num2)

现在你有一些变量,它们的名称与 function 中的名称相同,但它们不同。 如果您从一开始就使用不同的名称,则不会出现此类问题,例如:

x1 = 11
x2 = 15
x1out = add_one(x1)
x2out = add_one(x2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM