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

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

  •  
  •   hnsxyhh · Sep 20, 2016 · 2963 views
    This topic created in 3520 days ago, the information mentioned may be changed or developed.
    一个脚本里封了很多类,我想将当前脚本里所有的类的名字都提取出来,该怎么写啊
    Supplement 1  ·  Sep 20, 2016
    class A:
    .....

    class B:
    .....

    class C:
    .....

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