Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python OOP和递归:何时放置;“自我”;什么时候不去_Python 3.x_Oop_Recursion_Self - Fatal编程技术网

Python 3.x Python OOP和递归:何时放置;“自我”;什么时候不去

Python 3.x Python OOP和递归:何时放置;“自我”;什么时候不去,python-3.x,oop,recursion,self,Python 3.x,Oop,Recursion,Self,在Python OOP中的递归函数中,前缀“self.”的使用似乎有点模糊 class Tree: def __init__(): ... def flatten(self, ...): nodeQueue = queue.Queue(10) ... nodeQueue.put(...) nodeQueue.get() ... self.flatten(...) ...

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

class Tree:
    def __init__():
        ...

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

      ...

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

      ...

      self.flatten(...)
      ...
问题1。若在递归的每一层都访问nodeQueue,那个么它应该是: self.nodeQueue或nodeQueue

问题2。由
..
表示的扁平化(…)参数是否也应该具有“self”前缀?具体地说,让其中一个参数为
layerDepth=0
。在每次递归调用时,
layerDepth+=1
发生。那么,应该是
self.layerDepth…
还是
layerDepth…


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

在方法的代码中:

  • 前缀为
    self.
    的变量名是从中调用方法的对象的成员字段
  • 未以
    self.
    作为前缀的变量名可以是该方法的局部(临时)变量,也可以是更大范围内的另一个变量(即全局变量)
也许这可以回答你的问题:

>x=5
>>>类别Myclass:
...   定义初始化(自):
...     self.x=3
...   def printme(自我):
...     打印(self.x)
...   他(自己):
...     打印(x)
... 
>>>o=Myclass()
>>>o.printme()
3.
>>>o.printhim()
5.
>>>其他类别:
...   定义初始化(自):
...     self.y=3
...   def printme(自我):
...     打印(self.y)
...   def printher(自我):
...     打印(y)
...   def print10(自):
...     y=10
...     打印(y)
... 
>>>o=其他类别()
>>>o.printme()
3.
>>>o.打印10()
10
>>>o.printher()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第7行,在printher中
名称错误:未定义名称“y”
>>>y=8
>>>o.printher()
8.
>>>o.打印10()
10
>>>o.printher()
8.
>>>印刷品(o.y)
3.
特别要注意的是,
print10
如何对外部变量
y
的值和
o.y
没有影响;从主作用域调用
o.y
,或者从
o
的方法调用
printme
引用
o
的相同成员字段
y