2016-11-17 85 views
0

我试图破译这些代码贴在几年前在这里:How to implement a binary search tree in Python?将自变量传递到新函数时发生了什么?

,我感到困惑的部分是本节:

class Node: 
    def __init__(self, val): 
     self.l_child = None 
     self.r_child = None 
     self.data = val 

def binary_insert(root, node): 
    if root is None: 
     root = node 
    else: 
     if root.data > node.data: 
      if root.l_child is None: 
       root.l_child = node 
      else: 
       binary_insert(root.l_child, node) 
     else: 
      if root.r_child is None: 
       root.r_child = node 
      else: 
       binary_insert(root.r_child, node) 

类和功能,然后通过这样叫:

r = Node(3) 
binary_insert(r, Node(7)) 
binary_insert(r, Node(1)) 
binary_insert(r, Node(5)) 

我的问题是:传递到binary_insert函数时发生了什么self.data? node.data和root.data来自哪里?

+0

'self'是'Node'类的实例.'root'和'node'都是'Node'类的实例。按照...... * self = root的方式思考它。 self.data * – Bahrom

回答

0

Python使用self作为类的一种方式来引用它自己的属性。一旦调用了该实例的方法,Python就会隐式地将自己填充到您的类实例中。

传递到binary_insert函数时发生了什么self.data?

什么都没有。 Node对象的一个​​实例被传入binary_searach函数。传入该函数的对象Node仍具有对象Node的所有属性,包括self.data

node.data和root.data从哪里来?

正如您所看到的,您的函数以您的Node对象的两个实例作为其参数。传递给函数的两个节点对象仍具有原始类Node的所有属性。他们只是使用不同的别名。这可以直接通过打印rootnode参数的类型来观察:

在你的函数的开头,我们可以打印类型rootnode

def binary_insert(root, node): 
    print("The type of root is:", type(root)) 
    print("The type of node is:", type(node)) 
    ... 

即要求输出时:

The type of root is: <class 'Node'> 
The type of node is: <class 'Node'> 
The type of root is: <class 'Node'> 
The type of node is: <class 'Node'> 
The type of root is: <class 'Node'> 
The type of node is: <class 'Node'> 
The type of root is: <class 'Node'> 
The type of node is: <class 'Node'> 
+0

感谢这是非常有用的......我想我得到了它的大部分,但在过去,我会使用self.data作为自己的变量。那么如果我在代码中使用self.data会发生什么? – jessibird

+0

@jessibird你指的是什么代码? –

0

这些正是self.data发生的情况。 root.data访问rootdata属性,该属性是Node类的一个实例。