Why is the class attribute remembered?

Here is an example python module:

# foo.py class Foo(object): a = {} def __init__(self): print self.a self.filla() def filla(self): for i in range(10): self.a[str(i)] = i 

then I do it in python shell:

 $ python Python 2.7.2 (default, Jan 13 2012, 17:11:09) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from foo import Foo >>> f = Foo() {} >>> f = Foo() {'1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8} 

Why is the second time a not empty? I missed something trivial.

+2
python class
source share
3 answers

The problem is that a not connected. This is a property of a class, not an object. You want to do something like this:

 # foo.py class Foo(object): def __init__(self): self.a = {} print self.a self.filla() def filla(self): for i in range(10): self.a[str(i)] = i 
+3
source share

It is an attribute of a class, not an instance, and is created when the class is defined, and not when it is created.

For comparison:

 class Foo(object): def __init__(self): self.a = {} print self.a self.filla() def filla(self): for i in range(10): self.a[str(i)] = i 
+3
source share

Any get variable in the _init _ method will be a "local variable".

 class Foo(object): def __init__(self): self.a = 'local' #this is a local varable >>> f = Foo() >>> fa 'local' >>> Foo.a AttributeError: type object 'Foo' has no attribute 'a' 

Any variable outside the _init _ method will be a "static variable".

 class Foo(object): a = 'static' #this is a static varable def __init__(self): #any code except 'set value to a' >>> f = Foo() >>> fa 'static' >>> Foo.a 'static' 

If you want to define a "local variable" and a "static variable"

 class Foo(object): a = 'static' #this is a static varable def __init__(self): self.a = 'local' #this is a local variable >>> f = Foo() >>> fa 'local' >>> Foo.a 'static' 

To access the static value inside the _init _ method using self. _class _ .a

 class Foo(object): a = 'static' #this is a static varable def __init__(self): self.a = 'local' #this is a local variable self.__class__.a = 'new static' #access static value >>> f = Foo() >>> fa 'local' >>> Foo.a 'new static' 
+1
source share

All Articles