Python and object/class attrs - what's going on? -


Can anyone explain why dragon does the following?

  & gt; & Gt; & Gt; Square Fu (object): ... bar = [] ... & gt; & Gt; & Gt; A = fu ()> gt; & Gt; & Gt; B = FU ()> gt; & Gt; & Gt; A.bar.append (1) & gt; & Gt; & Gt; B. Bar [1] & gt; & Gt; & Gt; A.bar = 1> & gt; & Gt; & Gt; A.bar 1 & gt; & Gt; & Gt; B. Bar [1] & gt; & Gt; & Gt; A.bar = []> gt; & Gt; & Gt; A.bar []> gt; & Gt; & Gt; B. Bar [1] & gt; & Gt; & Gt; Del a.bar & gt; & Gt; & Gt; A.bar [1]  

This is misleading!

As others have said that the written code creates a class variable instead of an example variable To create a frequency variable, you need to assign __init __ .

Hopefully this annotated copy of your code is helpful in explaining what is happening at each stage:

  & gt; & Gt; & Gt; Square Fu (object): ... bar = [] Defines a class variable on #foo (shared by all instances) ... & gt; & Gt; & Gt; A = fu ()> gt; & Gt; & Gt; B = FU ()> gt; & Gt; & Gt; A.bar.append (1) # Adds the value 1 to the empty list first in Foo.bar> & Gt; & Gt; B.bar # class variable returns the value of Foo.bar [1] & gt; & Gt; & Gt; A.bar = 1 # this frequency variable at a.bar 1, binding access & gt; & Gt; & Gt; A.bar # You had to first class variables through 1 time;> gt; & Gt; & Gt; B.bar # b does not have an example variable 'bar', so it still returns back to [1] # square variable & gt; & Gt; & Gt; A.bar = [] # A frequency variable binding for an empty frequency; & Gt; & Gt; A.bar []> gt; & Gt; & Gt; B.bar # b does not have an example variable 'bar', so it still returns back to [1] # square variable & gt; & Gt; & Gt; Del a.bar # opens an example charge to unmasking square frequency; Gt; & Gt; & Gt; A.bar # so a.bar now returns a list with 1 in it. [1]  

Additionally, Foo.bar (what is the value delivered by you through the class after each statement) is happening It can help to clarify it.


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -