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-09-20 11:51:14 +08:00 · 2438 次点击
    这是一个创建于 2776 天前的主题,其中的信息可能已经有所发展或是发生改变。
    一个脚本里封了很多类,我想将当前脚本里所有的类的名字都提取出来,该怎么写啊
    第 1 条附言  ·  2016-09-20 15:01:13 +08:00
    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-09-20 12:00:05 +08:00
    see https://docs.python.org/3/library/modules.html
    (不认真看文档的打死好么?
    Geoion
        2
    Geoion  
       2016-09-20 12:16:14 +08:00
    self.__class__.__name__
    csdreamdong
        3
    csdreamdong  
       2016-09-20 12:42:12 +08:00
    globals()
    ?
    hnsxyhh
        5
    hnsxyhh  
    OP
       2016-09-20 19:53:39 +08:00
    是 python2.7 哦
    Contextualist
        6
    Contextualist  
       2016-09-20 20:06:25 +08:00 via iPad
    3 楼正解, globals() 返回所有全局变量的 dict ,然后只需要逐个用 type() 筛出是 class 的变量就行了。
    sheep3
        7
    sheep3  
       2016-09-20 20:23:08 +08:00
    cat `find ./ -iname '*.py'` | egrep 'class\s+[a-zA-Z]+\('
    errorlife
        9
    errorlife  
       2016-09-21 09:07:55 +08:00
    头像围观者:)
    xrlin
        10
    xrlin  
       2016-09-21 13:24:04 +08:00
    围观头像
    hnsxyhh
        11
    hnsxyhh  
    OP
       2016-09-21 15:48:23 +08:00
    谢谢大家,楼上几位的方法都试了, 8 楼的方案解决了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   879 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:52 · PVG 05:52 · LAX 14:52 · JFK 17:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.