需要您的帮助。有一个由类对象组成的列表(数组),如何找到列表中的项目(行),例如:手机还是名字?我有一个功能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