[英]Python : Object attributes overwritten when creating a new object
Here is a code I'm working on: 这是我正在处理的代码:
class Node:
count = 0
def __init__(self):
Node.id = Node.count
Node.count += 1
@classmethod
def get_count(cls):
return Node.count
class Element:
count = 0
def __init__(self, type = "MTH20", group = 0):
self.type = type
self.group = group
Element.count += 1
def define_element(self):
self.nodes = [-1]*3
for l in range(len(self.nodes)):
if self.nodes[l] == -1:
self.nodes[l] = Node()
print(self.nodes[l].id)
for l in range(len(self.nodes)):
print(self.nodes[l].id)
ga = Element()
ga.define_element()
I would expect the output of this code to be: 我希望此代码的输出为:
0
1
2
0
1
2
However I get this: 但是我得到这个:
0
1
2
2
2
2
My conclusion is that somehow the id attribute of a node object is overwritten when constructing a new node. 我的结论是,构造新节点时,某种程度上会覆盖节点对象的id属性。 However, I don't understand why it would do so, or how to avoid that.
但是,我不知道为什么会这样做,或者如何避免这种情况。
Can anyone point out what I did wrong? 谁能指出我做错了什么?
With Node.id
you are accessing a class attribute. 使用
Node.id
您可以访问类属性。 You want to store ids as instance attributes by doing self.id
. 您想通过执行
self.id
将id存储为实例属性。
class Node:
count = 0
def __init__(self):
self.id = Node.count # We want id to be an attribute of that specific node
Node.count += 1
I want to point out that your Element.define_element
method could be written in a more concise natural way. 我想指出,您的
Element.define_element
方法可以用更简洁的自然方式编写。
class Element:
...
def define_element(self):
self.nodes = [Node() for _ in range(3))]
for node in self.nodes:
print(node)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.