我想创建5个对象(序列号,部件号,卡名,卡状态,卡类型)。我的代码接收一个包含一些字符串的文件(有关每张卡的信息)。从代码中可以看出,我在main函数的for循环之前只创建了一个对象。我想在这里创建一个对象"在这里创建对象"。对象是卡,每张卡都有部件号,序列号,名称,状态和类型。当我运行此代码时,它只输出Card-Name,因为它只创建一个对象。但是,如果我将它们全部放在数组或字典中并输出,那么它将输出所有内容(再次因为它只创建一个对象)。如何让它输出所有这些信息。我知道我的问题在于我创建对象的方式。我是python的新手,所以任何帮助都会非常感激。此外,是的,我希望我的所有变量都是私有的。
###############
#output:
#Card-Name: CPM B
#Serial-Number:
#part-Number:
#Card-Status:
#Card-Type
##############
class Slot(object):
card_sn = ""
card_pn = ""
card_name = ""
card_status = ""
card_type = ""
def __init__(self):
self.__card_sn = ""
self.__card_pn = ""
self.__card_name = ""
self.__card_status = ""
self.__card_type = ""
def CPM_detail(self,input,region,subregion):
temp = re.search(r'(\s+)Card (A|B|C|D)',input)
if temp:
############
#would like to create the object here
############
self.__card_name = "CPM "+str(temp.group(2))
temp = re.search(r'Memory capacity',input)
if temp:
self.__card_type = temp.group(1)
temp = re.search(r'\s{10,}(\S+)\s{20,}',input)
if temp:
self.__card_status = str(temp.group(1))
temp = re.search(r'(\s+)Serial number(\s+): (\S+)',input)
if temp:
self.__card_sn = temp.group(3)
temp = re.search(r'(\s+)Part number(\s+): (\S+)',input)
if temp:
self.__card_pn = temp.group(3)
def serial_number(self):
return self.__card_sn
def part_number(self):
return self.__card_pn
def card_name(self):
return self.__card_name
def card_status(self):
return self.__card_status
def card_type(self):
return self.__card_type
def main():
with open ('/home/thamer/TS_ncren202_XRS-20_20150624_12.0.R6.txt','r') as f:
slot_cards = Slot()
for line in f:
slot_cards.CPM_detail(line,region,subregion)
serialNumber = slot_cards.serial_number()
partNumber = slot_cards.part_number()
cardName = slot_cards.card_name()
cardStatus = slot_cards.card_status()
cardType = slot_cards.card_type()
print "Card-Name: ",cardName
print "Serial#: ",serialNumber
print "part#: ",partNumber
print "Card-Status: ",cardStatus
print "Card-Type ",cardType
if __name__ == '__main__':
main()