繁体   English   中英

如何访问对象列表中的 object 属性,该属性是 python 中 class 的属性?

[英]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.

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