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

如何获取当前脚本里所有的类名?

  •  
  •   hnsxyhh · 2016 年 9 月 20 日 · 2810 次点击
    这是一个创建于 3401 天前的主题,其中的信息可能已经有所发展或是发生改变。
    一个脚本里封了很多类,我想将当前脚本里所有的类的名字都提取出来,该怎么写啊
    第 1 条附言  ·  2016 年 9 月 20 日
    class A:
    .....

    class B:
    .....

    class C:
    .....

    if __name__ == '__main__'
    这里想定义一个函数将上面的类名 A,B,C 都取出来;新手搜了半天,没看到理想的结果,求大神指点。
    11 条回复    2016-09-21 15:48:23 +08:00
    Septembers
        1
    Septembers  
       2016 年 9 月 20 日
    see https://docs.python.org/3/library/modules.html
    (不认真看文档的打死好么?
    Geoion
        2
    Geoion  
       2016 年 9 月 20 日
    self.__class__.__name__
    csdreamdong
        3
    csdreamdong  
       2016 年 9 月 20 日
    globals()
    ?
    hnsxyhh
        5
    hnsxyhh  
    OP
       2016 年 9 月 20 日
    是 python2.7 哦
    Contextualist
        6
    Contextualist  
       2016 年 9 月 20 日 via iPad
    3 楼正解, globals() 返回所有全局变量的 dict ,然后只需要逐个用 type() 筛出是 class 的变量就行了。
    sheep3
        7
    sheep3  
       2016 年 9 月 20 日
    cat `find ./ -iname '*.py'` | egrep 'class\s+[a-zA-Z]+\('
    errorlife
        9
    errorlife  
       2016 年 9 月 21 日
    头像围观者:)
    xrlin
        10
    xrlin  
       2016 年 9 月 21 日
    围观头像
    hnsxyhh
        11
    hnsxyhh  
    OP
       2016 年 9 月 21 日
    谢谢大家,楼上几位的方法都试了, 8 楼的方案解决了
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   3105 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 96ms · UTC 13:30 · PVG 21:30 · LAX 05:30 · JFK 08:30
    ♥ Do have faith in what you're doing.