Skip to main content
 首页 » 编程设计

python之与 python 类声明的变量有些混淆

2025年05月04日15lyj

我有课

>>> class Foo: 
...     ls=[] 
... 
>>> f1=Foo() 
>>> f2=Foo() 
>>> f1.ls.append(1) 
>>> f1.ls.append(2) 
>>> print f1.ls 
[1, 2] 
>>> print f2.ls    
[1, 2]                #I expect its result is empty [], why 
>>> f2.ls=[] 
>>> print f1.ls        
[1, 2] 
>>> print f2.ls 
[] 
           # If f1.ls and f2.ls refer to the same list, since i modify f2.ls, 
           # the f1.ls is empty ,too. Does the statement 'f2.ls=[]' add new attribute 
           # to f2. Where do f1.ls and f2.ls refer and how it happens 

我想使用一个类并声明许多变量。如果我希望所有变量都有不同的列表。我这样做吗

class Foo: 
    pass 
f1=Foo() 
f2=oo() 
f1.ls=[] 
f2.ls=[] 
do others 

有没有一些更简单更好的方法。 原谅我对 python 类的无知。提前致谢

请您参考如下方法:

类级赋值创建类变量。要创建实例变量,请在构造函数中执行:

def __init__(self): 
    self.ls = []