不同之处在于,在第二个示例中,您正在创建一个新列表self.tricks作为对象的属性:
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(因为尚未创建),那么它将尝试将其作为类的成员来查找。由于有
技巧 ,因此您可以访问它。
如果您在第二个示例中尝试使用mytest.tricks,则可能对您很清楚:
def __init__(self,name): self.name=name mytest.tricks=[name] # <-- this is accesing the class attribute instead self.tricks.append(name)
这将输出您的实际期望。


![Python类中的属性是否共享?[重复] Python类中的属性是否共享?[重复]](http://www.mshxw.com/aiimages/31/634267.png)
