如何在设计新类时打印联系人列表的内容



我正在学习和试验Python。如何在第二个函数print_contacts中传递contact_list,以便它可以从contact_list打印名称?我确定我做错了什么,谁能解释一下为什么会这样?

class Contact(object):
contact_list = []
def __init__(self, name, email):
self.name = name
self.email = email
return Contact.contact_list.append(self)
# How to pass contact_list to below function?
def print_contacts(contact_list):
for contact in contact_list:
print(contact.name)

对我来说,让一个Contact对象也拥有一个contact_list属性没有任何意义,如果它是类范围的而不是实例化的,那就更少了。我会这样做:

class Contact(object):
def __init__(self, name, email):
self.name = name
self.email = email
def __str__(self):
return f"{self.name} <{self.email}>"
# or "{} <{}>".format(self.name, self.email) in older versions of
# python that don't include formatted strings

contacts = []
def print_contacts(contacts: "list of contacts") -> None:
for c in contacts:
print(c)
adam = Contact("Adam Smith", "adam@email.com")
contacts.append(adam)
bob = Contact("Bob Jones", "bob@email.com")
contacts.append(bob)
charlie = Contact("Charlie Doe", "charlie@email.com")
contacts.append(charlie)
print_contacts(contacts)
# Adam Smith <adam@email.com>
# Bob Jones <bob@email.com>
# Charlie Doe <charlie@email.com>

或者,对知道如何创建Contact对象并显示所有对象的AddressBook进行建模。

class AddressBook(list):
def add_contact(self, *args, **kwargs):
new_contact = Contact(*args, **kwargs)
self.append(new_contact)
def display_contacts(self):
for contact in self:
print(contact)
contacts = AddressBook()
contacts.add_contact("Adam Smith", "adam@email.com")
contacts.add_contact("Bob Jones", "bob@email.com")
contacts.add_contact("Charlie Doe", "charlie@email.com")
contacts.display_contacts()
class Contact(object):
contact_list = []
def __init__(self, name, email):
self.name = name
self.email = email
Contact.contact_list.append(self)
@classmethod
def print_contacts(cls):
for contact in cls.contact_list:
print(contact.name)
cont1 = Contact("John", "john@john.com")
cont2 = Contact("Mary", "mary@mary.com")
Contact.print_contacts()

将打印

>>John
Mary

回答你关于为什么你的代码目前不起作用的问题:首先,你的init方法不需要返回调用,init在对象创建时被调用以建立对象变量,并且通常不需要返回任何内容(特别是在这种情况下,因为 .append(( 不提供任何返回(。 其次,类方法似乎更适合你尝试使用第二种方法做的事情,你可以在这里阅读更多关于它的信息:Python 中的类方法有什么用?

相关内容

最新更新