首页 > 解决方案 > Python OOP 和递归:什么时候放“self”,什么时候不放

问题描述

在 Python OOP 中的递归函数中,使用前缀“self”。似乎变得有点模糊。

class Tree:
    def __init__():
        ...

    def flatten(self, ...):
      nodeQueue = queue.Queue(10)

      ...

      nodeQueue.put(...)
      nodeQueue.get()

      ...

      self.flatten(...)
      ...

Q1。如果在递归的每一层都访问nodeQueue,它应该是:self. 节点队列节点队列

Q2。用 表示的flatten(...)的参数...,是否也应该有“self”前缀?具体来说,设参数之一为layerDepth = 0。并且在每次递归调用中,layerDepth += 1都会发生。那么,应该是self.layerDepth ...ORlayerDepth ...

鉴于我的两个问题,我希望得到一个概述self.OOP 递归函数上下文中使用的一般规则的答案。

标签: python-3.xooprecursionself

解决方案


在方法的代码中:

  • 变量名前缀self.是您调用该方法的对象的成员字段;
  • 不带前缀的变量名self.要么是方法的局部(临时)变量,要么是更大范围的另一个变量(全局变量)。

也许这可以回答你的问题:

>>> x = 5
>>> class Myclass:
...   def __init__(self):
...     self.x = 3
...   def printme(self):
...     print(self.x)
...   def printhim(self):
...     print(x)
... 
>>> o = Myclass()
>>> o.printme()
3
>>> o.printhim()
5
>>> class Theotherclass:
...   def __init__(self):
...     self.y = 3
...   def printme(self):
...     print(self.y)
...   def printher(self):
...     print(y)
...   def print10(self):
...     y = 10
...     print(y)
... 
>>> o = Theotherclass()
>>> o.printme()
3
>>> o.print10()
10
>>> o.printher()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in printher
NameError: name 'y' is not defined
>>> y = 8
>>> o.printher()
8
>>> o.print10()
10
>>> o.printher()
8
>>> print(o.y)
3

特别要注意 howprint10对外部变量的值和 ; 没有y影响o.yo.y并且从主作用域或self.yo的方法调用printme是指相同的成员字段yo


推荐阅读