Python 类中的变量范围 [英] Variable scopes in Python classes
问题描述
在类中声明变量(函数外):所有类函数都可以访问它(基本上是公共变量)
Declaring a variable in a class (outside of a function): all class functions can access it (basically a public variable)
在类内的函数内声明变量:只有该函数可以访问它(它在该函数的范围内)
Declaring a variable inside a function inside a class: only that function can access it (it's in that function's scope)
在类内的函数内用self.(variable name)
声明变量:所有类函数都可以访问它(这与global(变量名)
?)
Declaring a variable with self.(variable name)
inside a function inside a class: all class functions can access it (how is this different from global (variable name)
?)
而且由于没有私有/受保护,所以一切都是公共的,因此可以从类内部访问的所有内容都可以从类外部访问.
And since there is no private/protected, everything is public, so everything accessible from inside a class is accessible from outside the class.
还有什么其他的细微差别我应该知道,或者我已经基本掌握了吗?
Are there any other nuances I should know, or have I pretty much got it?
推荐答案
由于您问题中的清单不是 100% 清楚,我决定用一个简单的例子来解释它.它还包括一些诸如 __something
变量之类的东西,您没有在列表中提及.
Since the listing in your question is not 100% clear, I've decided to explain it with a simple example. It also includes some things like __something
variables you did not mention in your list.
class Test:
a = None
b = None
def __init__(self, a):
print self.a
self.a = a
self._x = 123
self.__y = 123
b = 'meow'
一开始,a
和 b
只是为类本身定义的变量 - 可以通过 Test.a
和 Test 访问.b
而不是特定于任何实例.
At the beginning, a
and b
are only variables defined for the class itself - accessible via Test.a
and Test.b
and not specific to any instance.
创建该类的实例时(这会导致 __init__
被执行):
When creating an instance of that class (which results in __init__
being executed):
print self.a
没有找到实例变量,因此返回类变量self.a = a
:创建一个新的实例变量a
.这会隐藏类变量,因此self.a
现在将引用实例变量;要访问类变量,您现在必须使用Test.a
- 对
self._x
的赋值创建了一个新的实例变量.它被视为不是公共 API 的一部分"(也就是受保护的),但从技术上讲,它没有不同的行为. - 对
self.__y
的赋值创建了一个名为_Test__y
的新实例变量,即它的名字被破坏了,所以除非你使用被破坏的名字,否则它不能从外部访问班级.这可用于私有"变量. - 对
b
的赋值创建了一个局部变量.除了__init__
函数之外,它在任何地方都不可用,因为它没有保存在实例、类或全局范围内.
print self.a
doesn't find an instance variable and thus returns the class variableself.a = a
: a new instance variablea
is created. This shadows the class variable soself.a
will now reference the instance variable; to access the class variable you now have to useTest.a
- The assignment to
self._x
creates a new instance variable. It's considered "not part of the public API" (aka protected) but technically it has no different behaviour. - The assignment to
self.__y
creates a new instance variable named_Test__y
, i.e. its name is mangled so unless you use the mangled name it cannot be accessed from outside the class. This could be used for "private" variables. - The assignment to
b
creates a local variable. It is not available from anywhere but the__init__
function as it's not saved in the instance, class or global scope.
这篇关于Python 类中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!