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

请教 python 的面向对象和递归程序设计中, self 该如何理解?

  •  
  •   billgreen1 · 2015-04-30 08:41:48 +08:00 · 3194 次点击
    这是一个创建于 3285 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我对 python 不是太熟,基本的面向对象和递归都还能明白,但是两个结合起来就有点弄不清了,尤其加上 函数的 self 参数后。
    比如定义一个树后
    https://dl.dropboxusercontent.com/u/12733047/Pasted_Image_4_30_15__08_34.png
    我不明白的是:那个地方的
    path.append(self.left.to_list()) 与
    path.append(to_list(self.left))
    有什么区别。
    都是递归调用
    感觉挺难理解的。
    6 条回复    2015-05-03 06:23:37 +08:00
    155
        1
    155  
       2015-04-30 08:52:20 +08:00
    先过一遍基本语法, 这问题和递归及OO没关系.
    staticor
        2
    staticor  
       2015-04-30 09:14:58 +08:00
    self指实例自身 self.left 不就是你初始化后的左节点么.

    至于递归, 联想成计算阶乘的递归结构.
    clino
        3
    clino  
       2015-04-30 09:20:44 +08:00
    "path.append(to_list(self.left))"
    这里找不到 to_list 吧? 因为局部变量里没有 to_list,就要去全局变量里找,总之不会去你的这个class里找 to_list
    tomwen
        4
    tomwen  
       2015-04-30 09:24:13 +08:00   ❤️ 1
    to_list 是 Binary_Tree的一个方法;
    定义的时候只有有一个参数:self, 调用的时候不能再传入其他参数,只能通过self.to_list()或者instance.to_list()调用;

    而要通过to_list(self.left)来调用的话,传入的参数就不对了;除非在Binary_Tree的外部定义这个函数,再传入相应的参数。
    billgreen1
        5
    billgreen1  
    OP
       2015-04-30 10:00:15 +08:00
    谢谢 @155 @staticor ,特别感谢 @clino @tomwen ,你们的回答清楚明了,我现在明白啦
    yorTX9t
        6
    yorTX9t  
       2015-05-03 06:23:37 +08:00
    楼上的诸位,这里我问一下: python 是不支持尾递归优化的,为何这个 BinaryTree 的 insert 和 to_list 方法要这么写?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2877 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:31 · PVG 17:31 · LAX 02:31 · JFK 05:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.