如何创建类对象的动态列表?

2024-10-01 04:55:31 发布

您现在位置:Python中文网/ 问答频道 /正文

当尝试向我的cells类对象列表添加新元素时,我注意到所有列表值都是添加项的最后一个值。我使用append添加新项目。我怎样才能得到正确的答案?你知道吗

class cells:
  x=0

from cells import cells
a=[]

a.append(hucre)
a[0].x=10

a.append(hucre)
a[1].x=20

a.append(hucre)
a[2].x=30

print(a[0].x) #30 where must give me 10
print(a[1].x) #30 where must give me 20
print(a[2].x) #30 where must give me 10

Tags: 项目对象答案from列表whereclassme
2条回答

您应该创建类cells的新实例,而不是更改cells的类cells.x属性。你知道吗

因此,应该为类cells定义__init__方法(有关__init__的详细信息:linklink):

class cells:
    def __init__(self, x=None):  # default value of x is None
        self.x = x


hucre = cells()  # instantiating new cells object
print(hucre.x)

Out: 
None

将值附加到列表:

a = []   
a.append(hucre)
a[0].x = 10
print(a[0].x)

Out: 
10

创建新对象,否则将更改第一个对象:

hucre = cells(20)
a.append(hucre) # here .x is 20 already so you need no assignment 
print(a[1].x)

Out: 
20

……等等。您可以在paren中附加实例化的对象:

a.append(cells(30))
print(a[2].x)

Out: 
30

这是因为在类中,您在类的主体中定义了x,而不是它的__init__方法。这使得它成为一个类变量,对于类的所有实例都是相同的,如the documentation。你知道吗

相关问题 更多 >