python - Dictionary and array as class vs. instance variables -
This is an easy way to earn some points, please explain the following:
Class C: a = {} b = 0 c = [] def __init __ (self): self.x = {} def D (self, k, v): self X [K] = V itself A [K] = V; Self.b = v self.c.append (v) def out (self, k): print (self. X [k], self a [k], self b, self. C [0]) c = C () D = C () CD (1, 10) DD (1, 20) c. Out (1) d. Out (1) will produce the following:
Why a dictionary, a list and 'plain' variable behave differently is?
Edit: I was thinking that the question is clear but I have to write it in more detail:
I have a class with three characteristics, A, B and C. I make two class examples. I again call a method which modifies these attributes for each example. When I observe the properties, I feel that if any specialty is a dictionary, it is shared in all instances, whereas it is a 'plain' variable, it behaves as if for each candidate Will be different.
First of all, [] is not an array, it is a list The point here is how the resolution of the attribute and the variable variable work is done. Fu (object): a = {} b = 0 c = [] it creates a class with three attributes
with Are you ??? They are available from either class (for example, Foo.a ), or through class' example ( Foo () .a ). Attributes are stored in a special item called __Vinicial __ . Both are in class and one example (there are cases in which this is not true, but they are irrelevant here) but in the case of Foo , the example __ dict __ is empty When the example is created ??? So when you Foo () , then in fact you are reaching the same object in Foo.a . Now, again __init __ . adding square fu (object): # ... def __init __ (self): self.x = {} This class' Creates one attribute in __ dict __ , but in an example, so that you type Foo.x , only Foo () .x . This is also a different object in every example, while class attributes are shared by examples of all classes. Now you are adding your mutation method.
square fu (object): # ... def mutate (self, key, value): self.x [key] = value self.a [key] = value self.b = Value self .c.append (value) Do you remember that self.x = {} creates an example feature? Here is the self.b = value one exact thing ??? This class does not touch the attribute at all, it creates a new one which saves the shared portion for examples (how this reference works in Python. Assignment binds the name of an object, and the object Never modifies the name). But you self.a and auto.c รข ???? You change them in-place (because they are ineligible and you can do this) a ???? So in fact you are amending the original class attributes, so you can follow the change in other examples (as shared by them). self.x behaves differently, because it is not a class feature, but an example. You can only self.c A ???? If you print it, you will see it [10, 20] .
Comments
Post a Comment