Python:关于变量范围。为什么我不需要将x传递给Y? [英] Python: Regarding variable scope. Why don't I need to pass x to Y?

查看:212
本文介绍了Python:关于变量范围。为什么我不需要将x传递给Y?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码,为什么我不需要将x传递给Y?

  class X:
def __init __(self):
self.a = 1
self.b = 2
self.c = 3

class Y:
def A(self):
print(xa,xb,xc)

x = X()
y = Y()
yA()






感谢您的最佳答案,他们确实帮助我了解问题所在即对可变范围的误解。我希望我可以选择这两个作为正确的答案,因为它们是以他们自己的方式启发。

://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespacesrel =nofollow> The Python Tutorial :


尽管范围是静态确定的,但它们是动态使用的。
在执行期间的任何时候,至少有三个嵌套的作用域
,它们的命名空间可以直接访问:


  • 首先搜索的最内层作用域包含本地名称

  • 任何封闭函数的作用域(从最近的包围作用域开始搜索)都包含非本地作用域,而且
  • >
  • 非全局名称倒数第二个范围包含当前模块的元素
  • 全局名称最后一个范围(最后一次搜索)是包含内置命名空间的名称空间姓名


在您的情况下 x = X() x 放入全局命名空间。由于您没有在 YA (内部范围)中本地定义 x ,所以python使用上述规则搜索变量定义并发现'x'是在最外面的范围内定义的。因此,当您在 Y.A 中引用 x.a 时,它可以解决问题。


Consider the following code, why don't I need to pass x to Y?

class X:    
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

class Y:        
    def A(self):
        print(x.a,x.b,x.c)

x = X()
y = Y()
y.A()


Thank you to the top answers, they really helped me see what was the problem, namely misunderstanding regarding variable scope. I wish I could choose both as correct answer as they are enlightening in their own way.

解决方案

From The Python Tutorial:

Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

  • the innermost scope, which is searched first, contains the local names
  • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also
  • non-global names the next-to-last scope contains the current module’s
  • global names the outermost scope (searched last) is the namespace containing built-in names

In your case x=X() puts x into the global namespace. Since you did not define x locally in Y.A (innermost scope), python searches for the variable definition using the above rules and finds that 'x' is defined in the outermost scope. Therefore when you reference x.a in Y.A it resolves just fine.

这篇关于Python:关于变量范围。为什么我不需要将x传递给Y?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆