我正在学习和试验Python。如何在我的第二个函数contact_list
中传递print_contacts
,以便它可以打印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)
答案 0 :(得分:2)
对我来说,让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>
或者,建模一个知道如何创建AddressBook
个对象并显示所有对象的Contact
。
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()
答案 1 :(得分:1)
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()不提供任何返回)。其次,类方法看起来更适合你试图用第二种方法做的事情,你可以在这里阅读更多相关内容:What are Class methods in Python for?