self.variable.function()在python中的意思是通过类self变量访问方法
我正在阅读这个简单的二叉搜索树插入方法,下面是解决方案:self.variable.function()在python中的意思是通过类self变量访问方法,python,algorithm,data-structures,binary-search-tree,Python,Algorithm,Data Structures,Binary Search Tree,我正在阅读这个简单的二叉搜索树插入方法,下面是解决方案: class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): if self.data: if data < self.data:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data),
if self.right:
self.right.PrintTree()
if __name__ == "__main__":
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.PrintTree()
然后:
self.right.insert(data)
以及:
这叫什么?我需要对此进行回顾。正如您可以从
插入(self,data)
方法的内容中看到的那样,右
和左
实例属性用于保存节点
类型的对象,它们是对self
节点的两个子节点的引用。您引用的行调用了这个类中定义的方法,但是它们不是在self
实例上调用它们,而是在子节点上调用它们,因此它们将处理不同的数据。它们都只是方法调用,其中调用方法的对象是节点
实例的属性。感谢@chepner,因为响应是有意义的,非常感谢Adam
self.right.insert(data)
self.left.PrintTree()