简体   繁体   English

功能之外的Python列表范围

[英]Python list scope outside a function

I am having a problem which is hard to explain because there's a lot of code involve. 我遇到了一个难以解释的问题,因为其中涉及很多代码。 So it boils down to the following problem. 因此,归结为以下问题。

I am trying to access the list xxx outside the function foo but I am getting unexpected results. 我正在尝试访问foo函数外部的列表xxx ,但得到了意外的结果。 Can someone please explain why? 有人可以解释为什么吗?

Here's my function which I have created to show the problem: 这是我创建的用来显示问题的函数:

def foo(xxx = []):
    if len(xxx) == 5:
        return xxx
    xxx += [1]
    foo()
    return xxx

If I run 如果我跑步

print foo()

I get 我懂了

[1, 1, 1, 1, 1]

which is what I expect. 这是我所期望的。

But I want the list xxx to be accessible outside foo. 但我想列表XXX到外面FOO访问。 So, I am doing 所以,我在做

xxx = []
print foo(xxx)
print xxx

Now I expect to get the list xxx to be 现在我希望得到列表xxx

[1, 1, 1, 1, 1]

but what I am getting xxx to be, is 但是我要成为的xxx

[1]

which is not what I expect. 这不是我所期望的。

Can someone explain why? 有人可以解释为什么吗? And is it possible to access the correct xxx outside foo without accessing it through the output of the function foo ? 并且可以在foo外访问正确的xxx而不通过函数foo的输出访问它吗? The reason I want to do this is because in my actual code I am returning something other than in my function foo and making changes to xxx which I want to see after the foo has executed. 我想这样做的原因是因为在我实际的代码,我在我的foo函数返回比其他的东西,使我想看到的FOO已被执行之后改变XXX。 I can make the function also return xxx every time but this will make my code unnecessarily bulky. 我可以使函数每次也返回xxx,但这会使我的代码不必要地笨重。 But I am not sure if I am compromising the code quality. 但是我不确定是否会损害代码质量。 I don't know. 我不知道。 Please suggest which ever way is the best. 请提出最好的方法。

Thanks 谢谢

xxx = []
print foo(xxx)
print xxx

In this code you are calling foo() with the list you created outside the function, called xxx . 在此代码中,将使用在函数外部创建的列表xxx调用foo() But within the function, you are recursing to call foo() without parameters, so it modifies the list that was created at function definition time by the expression for the default argument value. 但是在函数内,您将递归调用不带参数的foo() ,因此它将修改在函数定义时由默认参数值的表达式创建的列表。 (Importantly, this is the same list every time you call the function without supplying a value for that argument.) (重要的是,每次调用该函数时都提供相同的列表,但不提供该参数的值。)

Compare what happens when you define foo like this instead: 比较当您像这样定义foo时发生的情况:

def foo(xxx = None):
    if xxx is None:
        xxx = []
    if len(xxx) == 5:
        return xxx
    xxx += [1]
    foo()
    return xxx

... and what happens when you define it like this: ...以及像这样定义时会发生什么:

def foo(xxx = None):
    if xxx is None:
        xxx = []
    if len(xxx) == 5:
        return xxx
    xxx += [1]
    foo(xxx)
    return xxx

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

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