V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
invite
V2EX  ›  Python

Python 类成员相互引用一问

  •  
  •   invite · Mar 6, 2015 · 3102 views
    This topic created in 4077 days ago, the information mentioned may be changed or developed.

    定义一个类:

    class demo:
    name = 'baidu'
    info = { 'engine': demo.name }

    但是这样会报错,那应该怎么样才能相互引用呢?

    9 replies    2015-03-07 21:11:21 +08:00
    way2exluren
        1
    way2exluren  
       Mar 6, 2015
    …………
    class demo( ):
    name = 'baidu'

    a = demo()

    info = {'engine':a.name}
    way2exluren
        2
    way2exluren  
       Mar 6, 2015
    定义了demo只是定义了一种类型。而字典是要求键值是实例。
    PS:好好看书……在网上问来的都是零散的知识,这样学不大好。
    系统的好好看完一本书……
    SevenJ
        3
    SevenJ  
       Mar 6, 2015
    class demo:
    name = 'baidu'
    info = { 'engine': name}
    sumhat
        4
    sumhat  
       Mar 6, 2015
    info = { 'engine': name }
    invite
        5
    invite  
    OP
       Mar 6, 2015
    @way2exluren 谢谢,你的解决方案不符合我的需求。 @SevenJ 的解决方案是王道。
    invite
        6
    invite  
    OP
       Mar 6, 2015
    @sumhat 谢谢。
    lincanbin
        7
    lincanbin  
       Mar 6, 2015
    没缩进有些不太了解你的意图。
    info是在类的说明里面吗?

    是类内部使用公共变量?还是类外部创建一个对象然后引用变量?
    如果是前者你直接使用即可;
    如果是后者,你没有创建对象。
    invite
        8
    invite  
    OP
       Mar 7, 2015
    @lincanbin 谢谢。

    两个都是类成员,如果只是上面一个类成员,访问没有问题的。

    前面的几位已有解决方案。
    luw2007
        9
    luw2007  
       Mar 7, 2015 via Android
    使用新式类写在__init__里比较容易理解。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2710 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 14:26 · PVG 22:26 · LAX 07:26 · JFK 10:26
    ♥ Do have faith in what you're doing.