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
Rabbit52
V2EX  ›  Python

问一个python的问题嘛

  •  
  •   Rabbit52 ·
    HugoPresents · 2012-09-03 22:34:53 +08:00 · 2794 次点击
    这是一个创建于 4245 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我有一个对象 a 它有一个属性 b 值为 c

    那么我 a.b 这样就能得到 c

    现在我有个变量 d = 'b'

    我怎么才能通过变量 d 拿到对象 a 中的 b 的值

    举个例子,如果在 php 中能这样 $a->$d
    5 条回复    1970-01-01 08:00:00 +08:00
    raptium
        1
    raptium  
       2012-09-03 22:39:27 +08:00   ❤️ 1
    a.__dict__[d]
    a.__getattr__(d)
    或者 a.__getattribute__(d) 也許更好
    yuelang85
        2
    yuelang85  
       2012-09-03 22:43:19 +08:00   ❤️ 1
    getattr(a, d)
    Rabbit52
        3
    Rabbit52  
    OP
       2012-09-03 22:57:32 +08:00
    @raptium
    @yuelang85
    谢谢你们! ok了!
    013231
        4
    013231  
       2012-09-03 23:08:59 +08:00
    你也可以實現類的__getitem__, __setitem__方法, 然後就可以像Javascript那樣用'[]'運算符訪問屬性了.
    Rabbit52
        5
    Rabbit52  
    OP
       2012-09-03 23:17:28 +08:00
    @013231 嗯,这个比较高端
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1182 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:16 · PVG 07:16 · LAX 16:16 · JFK 19:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.