推荐学习书目
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 · Apr 30, 2015 · 3821 views
    This topic created in 4032 days ago, the information mentioned may be changed or developed.
    我对 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 replies    2015-05-03 06:23:37 +08:00
    155
        1
    155  
       Apr 30, 2015
    先过一遍基本语法, 这问题和递归及OO没关系.
    staticor
        2
    staticor  
       Apr 30, 2015
    self指实例自身 self.left 不就是你初始化后的左节点么.

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

    而要通过to_list(self.left)来调用的话,传入的参数就不对了;除非在Binary_Tree的外部定义这个函数,再传入相应的参数。
    billgreen1
        5
    billgreen1  
    OP
       Apr 30, 2015
    谢谢 @155 @staticor ,特别感谢 @clino @tomwen ,你们的回答清楚明了,我现在明白啦
    yorTX9t
        6
    yorTX9t  
       May 3, 2015
    楼上的诸位,这里我问一下: python 是不支持尾递归优化的,为何这个 BinaryTree 的 insert 和 to_list 方法要这么写?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3389 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 11:25 · PVG 19:25 · LAX 04:25 · JFK 07:25
    ♥ Do have faith in what you're doing.