需要您的幫助。有一個由類對象組成的列表(數組),如何找到列表中的項目(行),例如:手機還是名字?我有一個功能findByName
和findByPhone
他們不工作!在對象列表中查找行
class Database:
name = 'n/a'
phone = 'n/a'
list = []
copy_list = []
class Rec:
def __init__(self, nam, phon):
self.name = nam
self.phone = phon
def __str__(self):
return "%s, %s" % (self.name, self.phone)
def __init__(self, fileName):
pass
def addRecord(self, name, phone):
self.list.append(Database.Rec(name,phone))
def findByName(self, name):
res = self.findSubStr(name)
if len(res) == 0:
print ("Sorry, nothing match in names for " + name)
return res
def findByPhone(self, phone):
res = self.findSubStr(phone)
if len(res) == 0:
print ("Sorry, nothing match in phones for " + phone)
return res
def findSubStr(self, substr):
res = []
for el in self.list:
if substr in self.list:
res.append(el)
return res
def fun_input():
print ("Please enter the name")
name = raw_input()
print ("Please enter phone number")
phone = raw_input()
db.addRecord(name, phone)
def fun_output():
db.out()
def fun_find():
print ("Please choose an option for which you want to search:")
print ("1 - Find for name")
print ("2 - Find for phone number")
ph = int(raw_input())
if ph == 1:
print ("Please enter the name for find:")
phName = raw_input()
db.findByName(phName)
if ph == 2:
print ("Please enter the phone number for find:")
phPhone = raw_input()
db.findByPhone(phPhone)
縮進需要修復,但這與您陳述的問題無關。在修改縮進之後,你的代碼是兩個類,但是你如何使用你的函數?我沒有提示輸入和輸出。 – davedwards