python-3.x - 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 递归函数上下文中使用的一般规则的答案。
解决方案
在方法的代码中:
- 变量名前缀
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.y
。o.y
并且从主作用域或self.y
从o
的方法调用printme
是指相同的成员字段y
。o
推荐阅读
- javascript - 在网络表单上实施自动完成建议
- maven - 具有多个 wsdl 文件的相对 wsdlLocation
- android - WorkManager - 可以更改重试的 WorkRequest 最大退避时间吗?
- python - 合并ndarray图像
- hibernate - 同义词可以代替触发器吗
- python - tf.audio.decode_wav 如何获取其内容?
- reactjs - 运行 firebase deploy 时找不到 404 页面
- sql - 如果返回超过 1 个 MS SQL,则删除
- python - 如何使用 keras imagedatagenerator 为 unet 加载图像和掩码
- sql - 查询关系表 - SQL