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

请教一个问题(8.10)

  •  
  •   saximi · Aug 10, 2017 · 2374 views
    This topic created in 3223 days ago, the information mentioned may be changed or developed.
    class num:
    def __init__(self,v):
    self.v=v

    def double(self):
    return self.v*2


    x=num(2)
    bound=x.double
    print(bound.__self__)
    print(bound.__self__.v)

    上面的代码输出如下:
    <__main__.num object at 0x01D3B1D0>
    2

    我的问题是:
    1、bound 就是 self.v*2,也就是 4,它为什么会是 num 对象,这是根据什么规则来确定的?
    2、即使 self.v*2 是 num 对象,这个对象的 v 属性又该如何推算出来,怎么就是 2 了?
    恳请指点!感谢
    4 replies    2017-08-11 23:39:01 +08:00
    187j3x1
        1
    187j3x1  
       Aug 10, 2017
    1. 你自己写的 x=num(2) 实例化对象
    2 b.__self__.v is x.v

    双下划线是魔术方法,基本知识自己 google 吧。
    ihciah
        2
    ihciah  
       Aug 11, 2017 via iPhone
    double 后面的小括号呢[斜眼笑]
    zhusimaji
        3
    zhusimaji  
       Aug 11, 2017
    @ihciah 有小括号就调用方法了,这个明显楼主没有调用这个的意思。
    给楼主贴上代码
    https://gist.github.com/zhusimaji/0dd5cd4bc96d52f62da2a029f841b326
    你在调用的 bound 的时候只是返回了 num 实例的内部成员函数,可以理解为类似你构造生成器对象,此时并没有立即调用 bound 函数,只有在使用 bound()时才会返回 4,具体你可以看我提交的代码
    saximi
        4
    saximi  
    OP
       Aug 11, 2017
    @zhusimaji 感谢大家指点,因为网络问题,我暂时打不开 gist 网址,但是我查了一些资料,对这个问题感觉明白了,我的理解如下:
    1、bound 变量指向了 x.double 这个方法,但并未调用该方法
    2、方法名.__self__ 指的就是这个方法的 self 参数,例子中是 double 方法的 self 参数,即 x,它是一个 num 对象,这就是第一个输出的由来。
    3、正因为 bound.__self__是 num 对象 x,所以 bound.__self__.v 也就是 x 的 v 属性,在这个例子中是 2

    我的理解没错吧?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3759 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    ♥ Do have faith in what you're doing.