Python 变量范围和类 [英] Python Variable Scope and Classes
问题描述
在 Python 中,如果我定义一个变量:
In Python, if I define a variable:
my_var = (1,2,3)
并尝试在类的__init__
函数中访问它:
and try to access it in __init__
function of a class:
class MyClass:
def __init__(self):
print my_var
我可以访问它并打印 my_var
而不声明(全局 my_var).
I can access it and print my_var
without stating (global my_var).
如果我把 my_var
放在 class MyClass
之后,我会得到范围错误 (no global variable found)
.
If I put my_var
right after class MyClass
however, I get scope error (no global variable found)
.
这是什么原因?我该怎么做?我在哪里可以阅读有关此内容的信息?我确实阅读了 Python Class 页面,但没有遇到它的解释.
What is the reason for this? How should I do this? Where can I read about this to learn? I did read Python Class page but I did not encounter its explanation.
谢谢
推荐答案
当你把它放在 class MyClass
之后,它就变成了一个类属性,你可以通过 MyClass 访问它.my_var
或类中的 self.my_var
(前提是您没有创建同名的 instance 变量).
When you put it right after class MyClass
, it becomes a class attribute and you can get access to it via MyClass.my_var
or as self.my_var
from within the class (provided you don't create an instance variable with the same name).
这是一个小演示:
my_var = 'global'
class MyClass(object):
my_var = 'class'
def __init__(self):
print my_var #global
print MyClass.my_var #class
print self.my_var #class -- Only since we haven't set this attribute on the instance
self.my_var = 'instance' #set instance attribute.
print self.my_var #instance
print MyClass.my_var #class
这篇关于Python 变量范围和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!