【问题标题】:What happened to the self variable when it's passed into a new function? [duplicate]将 self 变量传递给新函数时发生了什么变化? [复制]
【发布时间】:2017-04-01 08:46:40
【问题描述】:

我正在尝试破译几年前发布的这段代码: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))

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

【问题讨论】:

  • selfNode 类的实例。rootnode 也是 Node 类的实例。想一想...... self=root; self.data

标签: python function arguments


【解决方案1】:

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

self.data 在传入 binary_insert 函数时发生了什么?

什么都没有。 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'>

【讨论】:

  • 谢谢,这很有帮助...我想我得到了大部分,但在过去,我会使用 self.data 作为它自己的变量。那么如果我在代码中使用 self.data 会发生什么?
  • @jessibird 你指的是什么代码?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多