推荐学习书目
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
tywtyw2002
V2EX  ›  Python

问个关于 python 的 function 的问题

  •  
  •   tywtyw2002 · Feb 15, 2015 · 3520 views
    This topic created in 4177 days ago, the information mentioned may be changed or developed.
    最近看到一段代码就产生了疑问python中function是以什么形式的存在呢?
    class?
    代码如下

    def test():
    pass

    test.a = 100
    test.b = 200

    居然还可以给function赋值? 这个不是之前class的功能吗???

    dir(test) 之后发现返回的是一个list

    求指导。
    8 replies    2015-02-15 16:30:32 +08:00
    9hills
        1
    9hills  
       Feb 15, 2015
    Python一切皆对象。function 也不例外
    9hills
        2
    9hills  
       Feb 15, 2015
    http://woodpecker.org.cn/diveintopython/getting_to_know_python/everything_is_an_object.html

    比如所有函数都有 __doc__ 这个属性,你也可以增加新的属性上去。而且访问函数的属性不会执行函数
    icedx
        3
    icedx  
       Feb 15, 2015
    貌似Fuction 也是一个对象...

    不过dir() 返回的必然是List 吧...
    我觉得你想要的是type()
    tywtyw2002
        4
    tywtyw2002  
    OP
       Feb 15, 2015
    @icedx 我就是感觉 居然一个function 还能用func.xx的方式去赋值。。。。
    jiang42
        5
    jiang42  
       Feb 15, 2015
    @tywtyw2002 syntax都是虚的。。。还是得理解内在的东西啊

    C++我也能写出函数对象来。。。也可以用func.xx去赋值
    ruoyu0088
        6
    ruoyu0088  
       Feb 15, 2015
    所有的Python对象在C语言里面都是一个结构体。这个结构体的第二个字段指向表示这个对象的类型。例如函数a是一个结构体,它的第二个字段指向function这个对象。function对象里面定义了如何存取函数对象的__dict__属性:

    https://github.com/python/cpython/blob/c7688b44387d116522ff53c0927169db45969f0e/Objects/funcobject.c#L434

    读取__dict__属性时实际上调用如下的函数PyObject_GenericGetDict():

    https://github.com/python/cpython/blob/347107218fd0ca2ba0bcfe97280ec17e902cf8c6/Objects/dictobject.c#L3797

    看这个函数你就知道,function对象支持__dict__,但是只有在你第一次使用它时才会创建这个字典,所以不必担心每个函数都带一个不必要的字典对象,增加内存使用量。
    Melodic
        7
    Melodic  
       Feb 15, 2015
    Python中函数的地位比类牛×多了
    icedx
        8
    icedx  
       Feb 15, 2015
    @tywtyw2002 其实就是类 建议去阅读源码
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2715 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 14:08 · PVG 22:08 · LAX 07:08 · JFK 10:08
    ♥ Do have faith in what you're doing.