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

python 同时有方法和函数这两个概念?

  •  
  •   zhuer · Jul 25, 2015 · 3890 views
    This topic created in 3944 days ago, the information mentioned may be changed or developed.

    今天再看python的官方文档,有一些地方说“。。。defines the following functions”然后有一些地方说“The following methods”。

    12 replies    2015-07-26 15:16:16 +08:00
    iwdmb
        1
    iwdmb  
       Jul 25, 2015   ❤️ 1
    定義在 Class 裡面的叫作 method(方法)

    直接定義在程式碼裡的叫作 function(函數)
    dacapoday
        2
    dacapoday  
       Jul 25, 2015
    含有self参数的函数就是方法,我瞎掰的
    FrankFang128
        3
    FrankFang128  
       Jul 25, 2015
    方法是 OOP 的概念,函数是一般概念
    laoyuan
        4
    laoyuan  
       Jul 25, 2015
    sorted(list) 和 list.sort( ) 什么区别?
    sorted(list) 创建了一个新的对象,list.sort( ) 仅仅是修改list 所指向的数据对象
    举个栗子:
    l = [3, 2, 1]
    def f(l):
    l.sort()
    f(l)
    print l
    jimzhong
        5
    jimzhong  
       Jul 25, 2015
    有区别的,对于类是method,method也是一种函数把
    echo1937
        6
    echo1937  
       Jul 25, 2015   ❤️ 1
    python2:
    class中定义的def称为method,形参中有self的为绑定方法,无self的为未绑定方法;class之外定义的def称为function

    python3:
    取消了未绑定方法,统一归入function
    publicID001
        7
    publicID001  
       Jul 25, 2015 via Android
    @echo1937 bound method 和 unbound method 的区别并不在 self 参数上面,self 只是一个名字而已,用来代表被传入方法的实例(事实上你把所有的 self 全改成 this 代码也一样能运行)
    对于某个特定的类的实例方法(比如 Foo.bar),Foo.bar 是 unbound method,foo.bar 是 bound method
    publicID001
        8
    publicID001  
       Jul 25, 2015 via Android
    @echo1937 当然 Python 3 确实是取消了 unbound method 这个设定
    MetroWind
        9
    MetroWind  
       Jul 26, 2015
    就是个名字的规定而已,面向对象的习惯叫法。其实都是函数。
    kamushin
        10
    kamushin  
       Jul 26, 2015
    区别在于,实例会把自己传入方法。
    introom
        11
    introom  
       Jul 26, 2015   ❤️ 1
    我就以Python3为例子好了。

    首先呢,是有Method和Function的区别,他们的类型都不一样。function就是function,method就是method。

    其次呢,function可以通过descriptor protcol得到method,method呢也可以从__func__得到原本的function。 (记忆这样告诉我,现在没空翻CPython源代码确认)

    Python的一大精髓就是descriptor protocol,理解清楚这个了,这个问题的答案自然就揭晓了。

    Let the C code speak. ;)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2528 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 16:08 · PVG 00:08 · LAX 09:08 · JFK 12:08
    ♥ Do have faith in what you're doing.