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

关于方法和函数的问题

  •  
  •   MyLeoWind · 2015-11-23 12:33:54 +08:00 via Android · 2518 次点击
    这是一个创建于 3049 天前的主题,其中的信息可能已经有所发展或是发生改变。
    为什么"hello".upper()和 str.upper("hello")的结果是一样的呢?为什么我可以这么用?
    11 条回复    2015-11-23 20:05:26 +08:00
    ruoyu0088
        1
    ruoyu0088  
       2015-11-23 12:47:28 +08:00
    你用的是 Python2 还是 Python3?
    MyLeoWind
        2
    MyLeoWind  
    OP
       2015-11-23 12:48:18 +08:00 via Android
    @ruoyu0088 是 python3
    ruoyu0088
        3
    ruoyu0088  
       2015-11-23 12:55:54 +08:00
    先不说 str 这种内置类型,例如如果你自己定义了一个类 A ,它有一个方法 func1(self), func1 实际上就是一个普通的函数保存在 A.__dict__中,如果你运行 A.func1 就得到这个函数,然后 A.func1(...),就调用这个函数。其第一个参数可以是任何对象,甚至不需要是 A 的实例。

    在 Python 中函数定义了__get__方法,当你调用 a.func1 时,实际上得到的是调用 func1.__get__的返回值,它是一个 bound method 对象,该对象的__func__,__self__属性分别保存 A.func1 对象和 A 的实例 a ,而调用该对象时就会运行 A.func1(a)。
    rebornix
        4
    rebornix  
       2015-11-23 12:58:40 +08:00
    https://hg.python.org/cpython/file/tip/Lib/string.py#l231

    def upper(s):
    """upper(s) -> string

    Return a copy of the string s converted to uppercase.

    """
    return s.upper()

    str.upper("hello") 的实现可不就是 "hello".upper() 么
    knightdf
        5
    knightdf  
       2015-11-23 13:01:54 +08:00
    你应该知道有种东西叫 self
    ruoyu0088
        6
    ruoyu0088  
       2015-11-23 13:02:07 +08:00
    @rebornix string.upper 是 string 模块中定义的 upper 函数,和楼主的问题无关。
    Frapples
        7
    Frapples  
       2015-11-23 15:47:01 +08:00
    还记得在定义方法时需要显示声明 self 参数吗?"hello".upper()这样写 python 会帮你隐式的传递 self 参数,和 str.upper("hello")效果是一样的,但是写成 "hello".upper()更有“感觉”,这种写法其实是一种语法糖。
    Frapples
        8
    Frapples  
       2015-11-23 15:49:05 +08:00
    上面打字打错了,显示->显式,抱歉。
    hbkdsm
        9
    hbkdsm  
       2015-11-23 17:31:48 +08:00
    Ruby 大法好,压根就没有函数,全是方法
    MyLeoWind
        10
    MyLeoWind  
    OP
       2015-11-23 20:02:54 +08:00 via Android
    @ruoyu0088
    @Frapples
    感谢解答,我好像明白了。所以
    MyLeoWind
        11
    MyLeoWind  
    OP
       2015-11-23 20:05:26 +08:00 via Android
    @ruoyu0088
    @Frapples
    感谢解答,我好像明白了。所以教程里说的方法的第一个参数 self 是自动指向这个实例本身是这样一个意思啊。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2523 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:43 · PVG 23:43 · LAX 08:43 · JFK 11:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.