如何访问 object 列表中的 object 属性,它是 python 中 class 的属性?
How to access object atribute inside a list of objects that is an atribute of a class in python?
我正在尝试构建一个“节点”class,它具有 2 个值属性和一个 children“节点”列表。当我尝试访问 child 的 children 之一时,我只得到当前的 child 列表。
这是我正在做的事情:
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)
我做错了什么?
这是一个common gotcha related to using mutable default arguments。 Python 在函数定义期间初始化该列表,因此所有后续 node
实例都在访问(和 re-assigning)完全相同的列表引用。
解决此问题的方法是将默认值定义为 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()
我正在尝试构建一个“节点”class,它具有 2 个值属性和一个 children“节点”列表。当我尝试访问 child 的 children 之一时,我只得到当前的 child 列表。
这是我正在做的事情:
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)
我做错了什么?
这是一个common gotcha related to using mutable default arguments。 Python 在函数定义期间初始化该列表,因此所有后续 node
实例都在访问(和 re-assigning)完全相同的列表引用。
解决此问题的方法是将默认值定义为 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()