Python和可变范围 [英] Python and Variable Scope
问题描述
所以我最近刚接触Python,但是我似乎能够编写一些东西并使它工作.但是,我一直在尝试扩展我对事物在语言中的工作方式的了解,并将这个简单的文件放在一起会使我感到困惑.
So I am recently new to Python, but I seem to be able to program some stuff and get it working. However I've been trying to expand my knowledge of how things work in the language, and putting this simple file together confuses me.
class TestA:
def __init__(self):
self.varNum = 3
def printNum(self):
print(self.varNum)
class TestB:
varNum = 0
def __init__(self):
varNum = 3
def printNum(self):
global varNum
print(varNum)
a = TestA()
a.printNum()
b = TestB()
b.printNum()
TestA
的代码可以在屏幕上正确打印3.但是, TestB
的代码却给了我一个 NameError
,该代码说明:'varNum'未定义
.无论我是否有 global varNum
行,我都会收到该错误.
The code to TestA
prints 3 to the screen properly. However the code for TestB
instead gives me a NameError
stating that: 'varNum' is not defined
. And I get that error whether i have the global varNum
line there or not.
我想让我感到困惑的是,我看到 __ init __
函数是一个类构造函数.当我使用Java或C#之类的语言进行编程时,我已在构造函数外部声明了全局变量,以使它们的范围成为整个类.这在Python中不是问题吗?我编写的代码只是在所有内容上加上了 self.
标签.因为我只是想快速整理一些东西,但现在我想弄清楚这种语言.是 self.
在Python中制作类范围变量的唯一方法吗?还是还有其他方法?
I suppose what confuses me, is I see the __init__
function as a class constructor. And when I have programmed with languages such as Java or C# I've declared global variables outside of the constructor so that their scope is the whole class. Is that not a thing in Python? The code I've written I just kind of tagged self.
onto everything because I was just trying to get some stuff put together quickly, but I am trying to figure more out about the language now. Is self.
the only way in Python to make class scope variables? Or are there other ways?
感谢您的时间:)
推荐答案
在Python中,在类定义内而不是方法内声明的变量是类或静态变量:
In Python, variables declared inside the class definition, but not inside a method are class or static variables:
class TestB:
varNum = 0
这将创建一个类级别的 varNum
变量,但这不同于任何实例级别的 varNum
变量,因此您可以:
This creates a class-level varNum
variable, but this is distinct from any instance-level varNum
variable, so you could have:
class TestB:
varNum = 0
def __init__(self):
self.varNum = 3
b = TestB()
print(b.varNum) # print 3
print(TestB.varNum) # print 0
因此,类 TestB
应该以这种方式工作:
Thus, class TestB
should work in this way:
class TestB:
varNum = 0
def __init__(self):
self.varNum = 3
def printInstanceNum(self):
print(self.varNum)
def printClassNum():
print(TestB.varNum)
b = TestB()
b.printInstanceNum() # print 3
TestB.printClassNum() # print 0
请注意,由于方法 printClassNum()
中没有对实例对象的任何引用,因此我们不必将 self
用作参数.该方法实际上可能成为一种静态方法:
Note that since there's no any reference to instance object in method printClassNum()
, we don't have to put self
as an argument. The method could actually become a staticmethod:
class TestB:
varNum = 0
@staticmethod
def printClassNum():
print(TestB.varNum)