[英]some confusion with variables declared by python class
我有課
>>> 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 = []
直接在類內部定義變量將提供類級別的變量。 因此, ls
並非在所有實例中都是唯一的,而是類Foo
一個屬性。 但是,仍然可以通過您的實例訪問它。
class Foo:
ls = []
以便:
>>> f1 = Foo()
>>> f2 = Foo()
>>> Foo.ls.append(1)
>>> Foo.ls
[1]
>>> f1.ls
[1]
>>> f2.ls
[1]
實例級別變量對於每個實例都是唯一的,並且可以在__init__
函數中定義,如下所示:
class Foo:
def __init__(self):
self.ls = []
這樣,類Foo沒有屬性ls
。 相反,每個使用__init__
構造的實例都可以:
>>> f1 = Foo()
>>> f2 = Foo()
>>> Foo.ls.append(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class Foo has no attribute 'ls'
>>> f1.ls.append(1)
>>> f1.ls
[1]
>>> f2.ls
[]
當你說
class Foo:
ls=[]
ls
被定義為一個類變量,並且您創建的所有對象將具有一個具有相同名稱的變量,並且該變量將指向該類的ls
值中的當前值。
當你說
f1.ls.append(1)
您實際上是在更改原始對象。 這就是為什么更改也會在f2
反映出來的原因(因為它們都指向同一個對象)。 但是當你說
f2.ls = []
您實際上是在f2
對象上創建一個變量,該變量引用一個空列表對象。 現在, ls
對象不同於f1
的ls。 您可以通過此語句確認這一點
print f1.ls is f2.ls # Will print False
print f1.ls is Foo.ls # Will print True
如果您實際上想在創建對象時獲取新對象。 您必須創建一個實例變量,像這樣
class Foo:
def __init__(self):
self.ls = []
f1, f2 = Foo(), Foo()
print f1.ls is f2.ls # Will print False
現在,您將ls
綁定到該類的當前實例,並使它指向一個空列表。 因此,這對於每個實例而言都是不同的。
ls是您定義的靜態變量。 您可以在init中使用 self.ls,因此您可以在內存中使用不同的ls。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.