Python类中的属性是否共享? [英] Are the attributes in a Python class shared or not?
问题描述
以下代码困扰我:-
class mytest:
name="test1"
tricks=list()
def __init__(self,name):
self.name=name
#self.tricks=[name]
self.tricks.append(name)
t1=mytest("hello world")
t2=mytest("bye world")
print t1.name,t2.name
print t1.tricks,t2.tricks
输出为:-
hello world bye world
['hello world', 'bye world'] ['hello world', 'bye world']
meaning that the list tricks
is shared by the two instances t1 and t2, which has been explained in the section 9.3.5 of https://docs.python.org/3/tutorial/classes.html
但是,如果我执行以下代码:-
However, if I execute the following code:-
class mytest:
name="test1"
tricks=list()
def __init__(self,name):
self.name=name
self.tricks=[name]
self.tricks.append(name)
t1=mytest("hello world")
t2=mytest("bye world")
x=t1.tricks
if type(x) is list:
print 'a list'
elif type(x) is tuple:
print 'a tuple'
else:
print 'neither a tuple or a list'
print t1.name,t2.name
print t1.tricks,t2.tricks
输出如下:-
a list
hello world bye world
['hello world', 'hello world'] ['bye world', 'bye world']
现在,列表tricks
似乎不再由这两个实例t1和t2共享.
我的问题是,这里的机制是什么?
Now it seems that the list tricks
is no longer shared by those two instances t1 and t2.
My question is, what are the mechanics here?
推荐答案
区别在于,在第二个示例中,您将创建一个新列表self.tricks作为对象的属性:
The difference is that in your second example you are creating a new list, self.tricks, as an attribute of the object:
def __init__(self,name):
self.name=name
self.tricks=[name] # <-- this is creating the new attribute for the object
self.tricks.append(name)
第一个示例之所以有效是因为Python解析名称的方式:如果在对象中找不到self.tricks(因为尚未创建),那么它将尝试将其作为类的成员来查找.由于存在技巧,因此您可以访问它.
The first example works because of Python's way of resolving the names: If self.tricks cannot be found in the object (because it hasn't been created), then it tries to find it as a member of the class. Since tricks is there, then you can access it.
如果您在第二个示例中尝试使用mytest.tricks,这可能对您很清楚:
It may become clear to you if you try to use mytest.tricks in your second example:
def __init__(self,name):
self.name=name
mytest.tricks=[name] # <-- this is accesing the class attribute instead
self.tricks.append(name)
这将输出您的实际期望.
That will output what you are actually expecting.
这篇关于Python类中的属性是否共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!