Why class attribute is remembered?

2019-07-17 03:16发布

Here is a sample 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 this 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 the second time a is not empty? Am I missing something trivial.

标签: python class
3条回答
做个烂人
2楼-- · 2019-07-17 03:21

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

Compare:

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楼-- · 2019-07-17 03:27

The problem is that a is not bound. It is a property of the class, not the 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
查看更多
太酷不给撩
4楼-- · 2019-07-17 03:30

Any variable get set in _init_ method will be a 'local variable'.

class Foo(object):
    def __init__(self):
        self.a = 'local' #this is a local varable

>>> f = Foo()
>>> f.a
'local'
>>> Foo.a
AttributeError: type object 'Foo' has no attribute 'a'

Any variable outside of _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()
>>> f.a
'static'
>>> Foo.a
'static'

If you want define 'local variable' and '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()
>>> f.a
'local'
>>> Foo.a
'static'

To access static value inside _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()
>>> f.a
'local'
>>> Foo.a
'new static'
查看更多
登录 后发表回答