如何解决Python OOP和递归:何时放置“自我”,何时不放置
在Python OOP的递归函数中,使用前缀“ self”。似乎有点模糊。
class Tree:
def __init__():
...
def flatten(self,...):
nodeQueue = queue.Queue(10)
...
nodeQueue.put(...)
nodeQueue.get()
...
self.flatten(...)
...
Q1。如果在递归的每一层都访问了 nodeQueue ,则应为: 自我。 nodeQueue 或 nodeQueue
第二季度。由...
表示的 flatten(...)参数是否也应具有“ self”前缀?具体而言,让参数之一为layerDepth = 0
。在每次递归调用时,都会发生layerDepth += 1
。因此,应该是self.layerDepth ...
还是layerDepth ...
鉴于我的两个问题,我希望得到一个概述self.
在OOP的递归函数中使用的一般规则的答案。
解决方法
在方法代码中:
- 以
frame_system::Module::<T>::events()
为前缀的变量名是您从中调用该方法的对象的成员字段; - 不带前缀
self.
的变量名称要么是方法的本地(临时)变量,要么是更大范围的另一个变量( ie ,是全局变量)。 li>
也许这可以回答您的问题:
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
对外部变量print10
的值或y
的影响如何;并且从主作用域调用o.y
或从o.y
的方法self.y
调用o
指的是printme
的相同成员字段y
。 / p>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。