关于 python 作用域

发布于 2024-11-03 03:05:57 字数 453 浏览 1 评论 0原文

我已经在 stackoverflow 上阅读了有关 python 范围的内容并浏览了问题,但我想澄清一些事情。

我正在将一段代码提取到一个函数中,从我习惯的角度来看,它应该将它使用的所有变量作为参数。但是,在 python 中,变量地址是在运行时确定的,因此实际上不需要参数。由于我是 python 新手,我想知道是否还有其他我应该知道的含义或约定。

x = 5
x += 1
print x

上述代码的以下重构之间有什么区别:

def f(x):
  x += 1
  return x

x = 5
x = f(x)
print x

和:

def f():
  x++

x = 5
f()
print x

如果没有,那么是 python 中更常用或首选的方法之一吗?

I've read about python scopes and browsed questions here on stackoverflow but theres something i'd like to clarify.

I'm extracting a piece of code to a function, from what i used to it should take all the variables it's using as parameters. But, in python the variable address is determined at runtime so theres actually no need for the parameters. Since i'm new to python i wanted to know if there are other implications or conventions i should know about.

x = 5
x += 1
print x

is there any difference between the following refactoring of the above code :

def f(x):
  x += 1
  return x

x = 5
x = f(x)
print x

and:

def f():
  x++

x = 5
f()
print x

If not then, is one of the ways more commonly used or preferred in python ?

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

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

发布评论

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

评论(2

余厌 2024-11-10 03:05:57

如果不是绝对必要,最好不要使用全局变量。也就是说,在第二个示例中,您需要在引用 x< 之前声明 global x /代码>。

因此,第一种方式:

  • f 接受一个参数 x
  • 增量 x
  • 返回 x + 1
  • 全局 x 不受影响

第二种方式:

def f():
  global x
  x += 1

x = 1
f()
  • f 无参数
  • 递增全局x

PS Python 没有++ 运算符。改为使用 x += 1

It's preferred not to use global variables, if not absolutely necessary. That said, in the second example you'd need global x declared before you refer to x.

So, first way:

  • f takes an argument x
  • Increments x
  • returns x + 1
  • the global x is not affected

The second way:

def f():
  global x
  x += 1

x = 1
f()
  • f has no arguments
  • Increments the global x

P.S. Python has no ++ operator. x += 1 is used instead

千仐 2024-11-10 03:05:57

我赞成这个问题有两个原因:

1)

  • 从其他语言(C++ 和 Java)导入符号 x++ 是一种小罪;谁不曾心不在焉?
  • 不测试代码应该投反对票,这是正确的,因为它表示没有进行任何测试来尝试获得一定数量的观察结果,这太糟糕了
  • ,但是我发现了解有关范围、名称空间、全局/本地概念的愿望更值得称赞 由于一个近似的问题而被否决

2)

,而收到一个赞成的答案,而在我看来,其中包含一些不充分的术语,这当然是一种不令人满意的情况。对于可能发生有争议的辩论和令人困惑的描述的主题,术语尤其重要。

例如,

def f(x): 
    x++ 
    return x
  • 我不会说 f 接收参数 x,而是说 f 接收 x 作为一个论点。
  • x 不增加;相反:创建另一个对象时,其值是初始 x

    值增加的结果,

  • f 不会返回 x+1 > ,它返回具有增量值的新对象

EDIT 1

< em># f 接受参数 x

在调用 f(x) 中,我不会说 f 接收到一个参数参数 x,因为 x 不是绝对的参数。 x 仅在传递给函数时才相对于函数“成为”参数。所以我宁愿说,在调用 f(x) 中,函数 f 接收 x AS 参数。

可能会发生一次“参数 Y”,作为表达 “Y ,在将其作为参数传递给函数时考虑的时刻”的轻描淡写 >。这个轻描淡写的说法比较短;但我认为,在精确的解释下,这种简单的表达方式必须被禁止。

#Increments x

参考问题中写的代码(情况1),这句话有歧义,因为写的函数带有参数xx是指函数内的x还是函数外的x?你可能会说我吹毛求疵,但对于一个不太了解数据模型和函数工作原理的新手来说,这个问题是有效的。 Python 中的 f(x) 是什么意思? ,x 是按值传递还是按引用传递?可能是 f 内部的操作可以改变外部的 x ,为什么不呢,这正是我们正在讨论的,不是吗?这就是为什么最好使用与外部对象的任何名称不同的名称来命名 f 的参数;我认为和上一句一样:在精确的解释中,只能使用谨慎的句子和代码,以避免混淆歧义:

def f(N):
    N += 1
    return N
x = 5
x = f(x)
print x

并且需要说明的是,指令N += 1触发了创建一个值递增的新对象,并且本地标识符N将反弹到该新对象。此时,全局标识符x仍然绑定到与调用之前相同的对象。

# returns x + 1

f 不返回 x+1 ,它返回新分配给的新对象N 值增加

# 全局 x 不受影响

这意味着什么?在 之前,全局 x 的值为 5。之后,全局 x 的值为 6。在 f 内部执行操作期间,全局x 不受影响,没错:只有当新对象(实际上是它的地址..)返回到 f 外部时,赋值才会受到影响。执行x = f(x)时,全局x受到影响。但这句话“全局x不受影响”放在“返回x + 1”之后
。不,真的,我对这样的解释一无所知。

编辑1结束

..

关于第二种情况,

def f():
    global x 
    x += 1
  • 更愿意说 f 没有参数,而不是没有参数。
  • 它没有' t 递增全局 x,它会引发将全局标识符 x 分配给具有递增值的新对象

编辑 2

在这种情况下,不可能在函数中使用除 x 之外的其他名称,否则示例将意味着另一件事

def f():
    global x
    x += 1
x = 5
f()
print x

# f 没有参数

我到底为什么要写 <. em>“我更喜欢说 f 没有参数而不是没有参数” 来评论这一点我仍然想知道。
首先,我写了“我更喜欢说 f 没有参数而不是没有参数”,考虑到 f 的定义。不知道为什么,我把句子颠倒过来“纠正”,结果却跟我想的完全不一样。我完全困惑了。

准确地说,我认为正确的表达方式是:

  • 在函数的定义中,f -> HAS没有PARAMETER,

  • 在调用f()中,f -> 接收无参数。

# 增加全局 x

它不会增加全局 x,而是引发全局标识符 x 的新分配strong> 到一个具有增量值的新对象。

编辑 2 结束

这看起来可能有些细微差别,但我确信这是一种以简洁的方式表达事物的方式。

但对我来说这非常重要,因为作为一个新手,由于这种不精确性,我很难理解所有这些与 Python 的特殊数据模型相关的问题,这些问题在 Python 的官方文档中解释得很糟糕,而且在尴尬的讨论中存在争议,例如关于“按值传递或按引用传递”的讨论(这在 Python 中没有意义),其中术语从右到左、从左到右浮动,就像在海洋中一样。模糊性。

I upvote the question for two reasons:

1)

  • importing the notation x++ from other languages (C++ and Java) is a venial sin; who has never been absent-minded ?
  • not testing codes deserves a downvote, that's right, because it denotes that no tests have been performed to try to obtain oneself a certain number of observations and that's baaad
  • however I find the desire to understand notions concerning scopes, namespaces, global/local more commendable than the faults to be reproached

2)

It is certainly an unsatisfactory situation to be downvoted because of an approximate question while receiving an upvoted answer that contains itself some inadequate terms according to me. Terminology is particularly important in subjects in which controversial debates and confusionning descriptions may happen.

For exemple, for

def f(x): 
    x++ 
    return x
  • I wouldn't say that f receives an argument x, but that f receives x as an argument.
  • x is not incremented; rather: another object is created with a value resulting of the incrementation of the value of initial x

  • f doesn't returns x+1 , it returns the new object with the incremented value

EDIT 1

# f takes an argument x

In the call f(x) , I wouldn't say that f receives an argument x, because x isn't an argument in the absolute. x "becomes" an argument only relatively to a function, at the moment when it is passed to the function. So I rather say that in the call f(x) , the function f receives x AS an argument.

It may happen that one says "the argument Y" one time, as an understatement to express "Y , considered at a moment when it is passed as an argument to a function". This understatement is shorter; but what I think is that in a precise explanation such an easy way to express must be banned.

#Increments x

Refering to the code written in the question (case 1), this sentence is ambiguous because of the function written with a parameter x: does x refer to the x in the function or the x outside ? You'll say I nitpick, but for a newbie that doesn't know the data model and the working of functions well, the question is valid. What does f(x) mean in Python ? , is the x passed by value or passed by reference ? It could be that the operations inside f could change the x outside, why not, that's precisely what is in discussion, no ? That's why it is preferable to name the parameter of f with a different name than any of the names of the outside objects; I think the same as for the previous sentence: in a precise explanation, only cautious sentences and codes should be employed, to avoid confusionning ambiguities:

def f(N):
    N += 1
    return N
x = 5
x = f(x)
print x

And it should be explained that the instruction N += 1 triggers the creation of a new object with value incremented and that the local identifier N is rebound to this new object. And at this point, the global identifier x is still bound to the same object as before the call.

# returns x + 1

f doesn't returns x+1 , it returns the new object newly assigned to N with the incremented value

# the global x is not affected

What does it mean ? Before , global x has a value 5. After, global x has a value 6. During the execution of the operations inside f, the global x isn't affected, that's right: it is only when the new object (in fact its address..) is returned to the outside of f, and that the assignement x = f(x) is executed that global x is affected. But this sentence "the global x is not affected" is placed after "returns x + 1
"
. No really, I understand nothing in such explanations.

End of EDIT 1

.

.

Concerning the second case

def f():
    global x 
    x += 1
  • I prefer to say that f has no argument than it has no parameter
  • It doesn't increments the global x, it provokes a new assignement of the global identifier x to a new object with incremented value.

EDIT 2

In this case, it isn't possible to use another name than x inside the function, otherwise the exemple would mean another thing.

def f():
    global x
    x += 1
x = 5
f()
print x

# f has no arguments

Why the hell did I write "I prefer to say that f has no argument than it has no parameter" to comment that ? I still wonder.
At first, I had written "I prefer to say that f has no parameter than it has no argument" , thinking to the definition of f . I don't know why, I "corrected" by reversing the sentence and the result expresses nothing of what I think. I am completely puzzled.

Precisely, I think that the correct manners to express are :

  • in the definition of the function, f -> HAS no PARAMETER,

  • in the call f() , f -> RECEIVES no ARGUMENTS.

# Increments the global x

It doesn't increments the global x, it provokes a new assignement of the global identifier x to a new object with incremented value.

End of EDIT 2

.

It may seem minor nuances , and I am sure that it is a way to express things in a condensed manner.

But for me it is very important because, when a newbie, I had a lot of difficulty because of this kind of imprecision to understand all these questions linked to the peculiar data model of Python that are badly explained in the official docs of Python and that are debated in awkard discussions, such as the one concerning "pass by value or pass by reference" for exemple (that has no sense in Python), in which the terms are floating from right to left and left to right like on a sea of vagueness.

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