繁体   English   中英

如何访问对象属性?

[英]How are object attributes being accessed?

有些人可以帮助我解决以下代码中的current_root.data.tolist() == goal_node.tolist():吗? 就像我知道它首先通过将goal_node 和current_root 放入一个列表来比较它们。 但是.data到底在做什么?

此外,在current_root = node_q.pop(0) node_q 是一个对象列表。 那么 pop 函数究竟“弹出”了什么?

import numpy as np  # Used to store the digits in an array
import os  # Used to delete the file created by previous running of the program


class Node:
        def __init__(self, node_no, data, parent, act, cost):
            self.data = data
            self.parent = parent
            self.act = act
            self.node_no = node_no
            self.cost = cost

def exploring_nodes(node):
    print("Exploring Nodes")
    actions = ["down", "up", "left", "right"]
    goal_node = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])
    node_q = [node]
    final_nodes = []
    visited = []
    final_nodes.append(node_q[0].data.tolist())  # Only writing data of nodes in seen
    node_counter = 0  # To define a unique ID to all the nodes formed
    while node_q:
        current_root = node_q.pop(0)  # Pop the element 0 from the list
        if current_root.data.tolist() == goal_node.tolist():
            print("Goal reached")
            return current_root, final_nodes, visited

k = np.array([[4, 1, 3], [2, 5, 6], [7, 8, 0]])
root = Node(0, k, None, None, 0)
exploring_nodes(root)

关于比较:被比较的两个变量都是 numpy 数组,因此它们是一个类的实例而不仅仅是一个列表。 所以 .data 用于获取 numpy 数组的实际值。 .toList() 只是将它们都转换为一个列表,因此很容易比较它们是否相同

关于弹出:在这种情况下,它将删除列表的索引 0 并返回它。 当循环第一次循环时,它会返回节点值,因为这是列表中的原始值

就像我知道它首先通过将goal_node 和current_root 放入一个列表来比较它们。 但是 .data 到底在做什么?

因为current_root是一个对象,它不能直接存储其他东西,这就是为什么元素存储在一个名为data的属性中。

此外,在 current_root = node_q.pop(0) 中,node_q 是一个对象列表。 那么 pop 函数究竟“弹出”了什么?

如代码中所写:

current_root = node_q.pop(0)  # Pop the element 0 from the list

因为node_q是一个列表, node_q.pop(0)删除(弹出)位置 0 处的元素。在您的情况下,它删除位于索引 0 处的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM