V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
guotie
V2EX  ›  Python

python类的成员变量的一个问题

  •  
  •   guotie ·
    guotie · 2013-04-11 10:33:16 +08:00 · 5625 次点击
    这是一个创建于 4032 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class C1(object):
    a = 1

    class C2(object):
    def __init__(self):
    self.a = 1

    两种对类的定义中,变量a有什么区别?
    8 条回复    1970-01-01 08:00:00 +08:00
    nkliwenjian
        1
    nkliwenjian  
       2013-04-11 11:02:33 +08:00
    稍微有一点吧。C1的a是定义在类上面的,你可以直接C1.a来取到,C2则只能先实例化一个对象才能取到
    huangzxx
        2
    huangzxx  
       2013-04-11 12:37:37 +08:00
    补充楼上的 :)

    >>> import test
    >>> c1 = test.C1
    >>> c1
    <class 'test.C1'>
    >>> c1.a
    1
    >>> c2 = test.C2
    >>> c2
    <class 'test.C2'>
    >>> c2.a
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: type object 'C2' has no attribute 'a'
    >>> c2 = test.C2()
    >>> c2
    <test.C2 object at 0x7f5f8fee1350>
    >>> c2.a
    1
    >>>
    013231
        3
    013231  
       2013-04-11 12:46:13 +08:00
    第一個例子中, a是類的變量; 第二個例子中, a是實例的變量.

    print C1.a
    1
    print C2.a
    AttributeError: type object 'C2' has no attribute 'a'
    sphinxdwood
        4
    sphinxdwood  
       2013-04-11 13:48:54 +08:00
    3楼正解。
    hit9
        5
    hit9  
       2013-04-11 22:41:25 +08:00
    类也是对象,对象就有属性。前者中a就是类的属性,后者a是这个 类的一个实例的属性。 访问的顺序是: 如果实例没有a,python会去看看它的类有没有a这个属性。
    windviki
        6
    windviki  
       2013-04-12 16:57:59 +08:00
    简单的类实例计数:
    >>> class A:
    >>> a = 0
    >>> def __init__(self):
    >>> A.a += 1
    >>> print A.a

    >>> _a = A()
    1
    >>> _a.a
    1
    >>> _b = A()
    2
    >>> A.a
    2
    >>> _a.a
    2


    类级别的变量可以理解为类静态变量,它的值被所有实例共享。一个实例更改了它,另外实例读取的时候就是更改后的值。
    类的成员变量是每个实例独自维护。
    glancesx
        7
    glancesx  
       2013-04-13 14:21:14 +08:00
    前者类属性,后者数据属性.
    hexor
        8
    hexor  
       2013-04-14 12:00:03 +08:00
    诶 这不是挺简单的事儿吗 我来说清楚好了

    前者的a 是所有对象甚至是没有对象的时候 都可以调用和修改的 直接通过 C1.a 就可以进行调用和修改

    后者的a 是每个对象自己的东西 比如说你新建了两个C2类的对象 o1 o2 那么 o1.a 与 o2.a 由这两个对象o1 o2分别维护.


    class C1(object):
    a = 1

    class C2(object):
    def __init__(self):
    self.a = 1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2963 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:30 · PVG 08:30 · LAX 17:30 · JFK 20:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.