[英]How to access object atribute inside a list of objects that is an atribute of a class in python?
我正在嘗試構建一個“節點”class,它具有 2 個值屬性和一個子“節點”列表。 當我嘗試訪問孩子的其中一個孩子時,我只得到當前的孩子列表。
這是我在做什么:
class node:
def __init__(self, value = 0, depth = 0, child = []):
self.value = value
self.depth = depth
self.child = child
a = node(1,0)
b = node(2,1)
c = node(3,1)
print("object A:",a)
print("object B:",b)
print("object C:",c)
# b and c have no children
print("Children of B:",b.child)
print("Children of C:",c.child)
a.child.append(b)
a.child.append(c)
# a now has 2 children, b and c
print("Children of A:",a.child)
# If I check "B" and "C" values it works ok
print("Value of B:",a.child[0].value)
print("Value of C:",a.child[1].value)
# but if I try to check b or c child list, I get A's children
print("Children of B:",a.child[0].child)
print("Children of C:",a.child[1].child)
我究竟做錯了什么?
這是與使用可變默認值 arguments 相關的常見陷阱。 Python 在 function 定義期間初始化該列表,因此所有后續node
實例都在訪問(並重新分配)相同的列表引用。
解決這個問題的方法是將默認值定義為None
,並在__init__
方法體內初始化列表:
def __init__(self, value=0, depth=0, children=None):
self.children = children or list()
...
要修復此問題,請在構造函數中使用列表的copy()
方法,只分配值而不是列表引用。
def __init__(self, value = 0, depth = 0, child = []):
self.value = value
self.depth = depth
self.child = child.copy()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.