我正在尝试打印对象(记录)的列表(电话簿),但是我是python的新手,并且它无法识别记录是列表中的对象。在这种情况下如何调用对象?
我尝试查看python的循环教程,但没有一个参考如何调用列表中的对象。
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
class PhoneBook:
def __init__(self):
self.phonebook = []
def printphonebook(self):
for record in self.phonebook:
x = 0
print(self.phonebook[x])
x = x + 1
预期的输出将是对象列表,包括电话号码,姓氏和名字。
答案 0 :(得分:2)
您要打印类的实例。因此,您应该提供特殊的__str__
方法来告诉python如何打印对象。 __str__()
必须返回一个字符串:here文档。
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
def __str__(self):
#returning a string with the content, you can edit the string to fit your needs.
#here I am using formatted string literals, works with python >= 3.6
return f"Last name: {self.lastname}, First Name: {self.firstname}, Telephone: {self.telephone}"
class PhoneBook:
def __init__(self):
self.phonebook = []
def printphonebook(self):
for entry in self.phonebook:
print(entry)
这里发生的是,当您调用print(record)
时,__str__()
方法用于提供表示实例内容的字符串。
因此,如果您这样做:
book = PhoneBook()
book.phonebook.append(record(800, "Wayne", "Bruce"))
book.phonebook.append(record(1234, "Kent", "Clark"))
book.phonebook.append(record(499, "Prince", "Diana"))
book.printphonebook()
这将打印:
姓氏:Wayne,名字:Bruce,电话:800
姓氏:Kent,名字:Clark,电话:1234
姓:Prince,名字:Diana,电话:499
答案 1 :(得分:0)
self.phonebook
中没有元素。当然,它什么也不打印。x=0
的迭代,因此您始终将打印第一项:class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
class PhoneBook:
def __init__(self):
self.phonebook = [1,2,3,4,5]
def printphonebook(self):
for record in self.phonebook:
x = 0
print(self.phonebook[x])
x = x + 1
a = PhoneBook()
a.printphonebook()
1
1
1
1
1
x
索引确实毫无意义,您只需打印record
:class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
class PhoneBook:
def __init__(self):
self.phonebook = [1,2,3,4,5]
def printphonebook(self):
for record in self.phonebook:
print(record)
a = PhoneBook()
a.printphonebook()
1
2
3
4
5
因此:1.用任何元素填充self.phonebook
。2.打印record
,不带索引。