为什么要记住类属性? [英] Why class attribute is remembered?

查看:56
本文介绍了为什么要记住类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例python模块:

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

然后我在python shell中执行此操作:

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}

为什么第二次 a 不为空?我错过了一些琐碎的事情吗?

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

推荐答案

问题是 a 是不束缚。它是类的属性,而不是对象。您想执行以下操作:

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

这篇关于为什么要记住类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆