为什么类属性会被记住?

2024-01-26

这是一个示例 python 模块:

# 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

然后我在 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}

为什么第二次a是不是空了?我是否错过了一些微不足道的事情。


问题是a没有绑定。它是类的属性,而不是对象的属性。你想做这样的事情:

# 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么类属性会被记住? 的相关文章

随机推荐