我刚开始用Python学习OOP,我一直在创建一个地址簿。我现在遇到的问题是我的for
循环没有显示我的数组的内容,而且我不完全确定原因?
代码实际上是我使用OOP制作的另一个短程序的副本,即for
循环与其他程序完全相同的代码,唯一的区别是被调用的数组的名称
我觉得在导致问题的for
循环之前某处可能是一个小错误,可能需要另一只眼睛来发现错误。
以下是代码:
#create Contacts class
class Contacts():
def __init__(self, firstName, lastName, address, telephone, mobile, email):
self.firstName = firstName
self.lastName = lastName
self.address = address
self.telephone = telephone
self.mobile = mobile
self.email = email
def showDetails(self):
print("First Name:\t", self.firstName)
print("Last Name:\t", self.lastName)
print("Address:\t", self.address)
print("Telephone:\t", self.telephone)
print("Mobile:\t", self.mobile)
print("Email:\t", self.email)
#initialise empty array
contactsList = []
while True:
#add contacts
firstName = input("First Name: ")
lastName = input("Last Name: ")
address = input("Address: ")
telephone = input("Telephone: ")
mobile = input("Mobile: ")
email = input("Email: ")
print("\n")
contact = Contacts(firstName, lastName, address, telephone, mobile, email)
contactsList.append(contact)
answer = input("Do you want to add more contacts? ")
print("\n")
if answer == "no":
break
elif answer == "yes":
continue
#For Loop not showing anything?
for i in contactsList:
i.showDetails
运行程序时,Python模块不会显示任何错误。
答案 0 :(得分:2)
您需要实际调用 showDetails()
方法:
for i in contactsList:
i.showDetails()
仅仅引用该方法不会调用它。
答案 1 :(得分:2)
showdetails
是会员功能。要调用,您需要附加()
:
i.showDetails()