Python 3.x Python OOP和递归:何时放置;“自我”;什么时候不去
在Python OOP中的递归函数中,前缀“self.”的使用似乎有点模糊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(...) ...
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