如何在Python中的类中创建列表? [英] How do I create lists in classes in Python?
本文介绍了如何在Python中的类中创建列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Python中的类中操作本地列表。我不能这样做:
class cCompetition:
lcPersonAll = []
def AddPerson(self,cPersonNew):
lcPersonAll.append(cPersonNew)
cCompetition1 = cCompetition()
cCompetition1.AddPerson( Smith)
但是,全球清单是可能的。
我尝试过:
创建不同的构造函数。
解决方案
使用 self 作为前缀
class cCompetition:
self.lcPersonAll = []
def AddPerson(self,cPersonNew):
self.lcPersonAll.append( cPersonNew)
你忘了将self添加到类变量lcPersonAll
self.lcPersonAll.append( cPersonNew)
我们通过self.lcPerson所有你会为你工作,因为python是面向对象的
self.lcPersonAll .append(cPersonNew)
I want to operate a local list in a class in Python. I can not do that:
class cCompetition:
lcPersonAll = []
def AddPerson(self, cPersonNew):
lcPersonAll.append(cPersonNew)
cCompetition1 = cCompetition()
cCompetition1.AddPerson("Smith")
However, global list is possible.
What I have tried:
To create different constructors.
解决方案
use self as prefix
class cCompetition: self.lcPersonAll = [] def AddPerson(self, cPersonNew): self.lcPersonAll.append(cPersonNew)
You forgot to add self to the class variable lcPersonAll
self.lcPersonAll.append(cPersonNew)
using the self.lcPersonAll you it will work for you as python is object-oriented
self.lcPersonAll.append(cPersonNew)
这篇关于如何在Python中的类中创建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文