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

Python 中如何查看一个函数都有什么参数

  •  
  •   smallpython · 2019-10-22 14:59:27 +08:00 · 8176 次点击
    这是一个创建于 1646 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如查看一个类有什么方法有内置的 dir()

    那么查看一个函数有什么参数有什么内置方法吗?
    10 条回复    2019-10-22 16:59:53 +08:00
    dji38838c
        1
    dji38838c  
       2019-10-22 15:02:42 +08:00
    help()
    arrow8899
        2
    arrow8899  
       2019-10-22 15:09:35 +08:00
    def method(a, b, c):
    ----pass

    print(method.__code__.co_varnames) # => ('a', 'b', 'c')
    Latin
        3
    Latin  
       2019-10-22 15:11:10 +08:00
    renmu
        4
    renmu  
       2019-10-22 15:11:15 +08:00 via Android
    pycharm 输入函数追踪进去(逃
    Anybfans
        5
    Anybfans  
       2019-10-22 15:28:55 +08:00   ❤️ 1
    In [1]: import inspect

    In [2]: def f(arg1, arg2):
    ...: print arg1, arg2

    In [3]: inspect.getargspec(f)
    Out[3]: ArgSpec(args=['arg1', 'arg2'], varargs=None, keywords=None, defaults=None)
    ClericPy
        6
    ClericPy  
       2019-10-22 15:43:21 +08:00   ❤️ 1
    楼上除了 5 楼有点贴近, 其他都像混子啊...

    前两天刚实现了一个自动把 function 转 UI 的, 正好用到了这方面的内省知识

    首先最推荐的是 inspect.signature, 具体用法看文档

    其次是 5 楼类似那个的 inspect.getfullargspec, 这个比 5 楼那个得到的更全面一点, 不过归类做的不如 signature 好
    locoz
        7
    locoz  
       2019-10-22 16:26:48 +08:00   ❤️ 1
    这个叫内省,其实 Google 搜一下就知道了,在论坛上问反而效率低,因为很多人都不会用到
    BigBug00
        8
    BigBug00  
       2019-10-22 16:55:13 +08:00
    在 pycham 里按住 shift 点进去
    smallpython
        9
    smallpython  
    OP
       2019-10-22 16:57:46 +08:00
    @ClericPy
    @locoz
    感谢
    smallpython
        10
    smallpython  
    OP
       2019-10-22 16:59:53 +08:00
    @arrow8899 你这个厉害了, 是不是那些包的内部也是调用的你这个方法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   960 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:19 · PVG 05:19 · LAX 14:19 · JFK 17:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.