簡體   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