问题描述
im有一个问题,了解如何类/实例变量在python中工作。我不明白为什么当我尝试这个代码列表变量似乎是一个类变量
class testClass():
list = []
def __init __(self):
self.list.append('thing')
p = testClass()
print p.list
f = testClass()
print f.list
['thing']
['thing','thing']
当我这样做它似乎是一个实例变量
class testClass():
def __init __(self):
self.list = []
self.list.append('thing')
p = testClass()
print p.list
f = testClass()
print f.list
输出:
['thing']
['thing']
非常感谢
jon
解决方案这是因为Python使用
解析名称。
。当你写self.list
Python运行时试图解析list
名称首先在实例对象中查找它,code> self.list.append(1)
- 在对象
self
中有列表
名称?
- 是:使用它!
- 有
list
name添加到对象self
的类实例中?
- 是:使用它!完成
>但是当你绑定一个名字的东西是不同的:self.list = []
列表
c $ c> self ?
- 是:覆盖它!
- 否:绑定!
所以,这总是一个实例变量。
你的第一个例子创建一个
list
到类实例中,因为这是当前的活动范围(任何self
)。但是你的第二个例子在self
范围内显式创建一个列表
。
更有趣的例子:
class testClass():
list = ['foo ']
def __init __(self):
self.list = []
self.list.append('thing')
x = testClass $ b print x.list
print testClass.list
del x.list
print x.list
这将打印:
['thing']
['foo' ]
['foo']
删除实例名称的时候,通过
self
引用可见。im having a problem understanding how class / instance variables work in python. I dont understand why when i try this code the list variable seems to be a class variable
class testClass(): list = [] def __init__(self): self.list.append('thing') p = testClass() print p.list f = testClass() print f.list
output:
['thing'] ['thing', 'thing']
and when i do this it seems to be an instance variable
class testClass(): def __init__(self): self.list = [] self.list.append('thing') p = testClass() print p.list f = testClass() print f.list
output:
['thing'] ['thing']
many thanks
jon
解决方案This is because of the way Python resolves names with the
.
. When you writeself.list
the Python runtime tries to resolve thelist
name first looking for it in the instance object, and if not found in the class instance.Let's look into it step by step
self.list.append(1)
- Is there a
list
name into the objectself
?
- Yes: Use it! Finish.
- No: Go to 2.
- Is there a
list
name into the class instance of objectself
?
- Yes: Use it! Finish
- No: Error!
But when you bind a name things are different:
self.list = []
- Is there a
list
name into the objectself
?
- Yes: Overwrite it!
- No: Bind it!
So, that is always an instance variable.
Your first example creates a
list
into the class instance, as this is the active scope at the time (noself
anywhere). But your second example creates alist
explicitly in the scope ofself
.More interesting would be the example:
class testClass(): list = ['foo'] def __init__(self): self.list = [] self.list.append('thing') x = testClass() print x.list print testClass.list del x.list print x.list
That will print:
['thing'] ['foo'] ['foo']
The moment you delete the instance name the class name is visible through the
self
reference.这篇关于python类实例变量和类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!