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

2024-04-26 02:58:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习和试验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)

Tags: to函数nameself名称objectinitemail
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>

或者,对一个知道如何创建Contact对象并显示它们的AddressBook建模。在

^{pr2}$
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()

将打印

^{pr2}$

要回答您的代码当前为什么不工作的问题:首先,您的init方法不需要返回调用,init在创建对象时被调用以建立对象变量,并且通常不需要返回任何内容(特别是在这种情况下,因为.append()不提供任何要返回的内容)。第二,类方法似乎更适合您尝试用第二种方法做什么,您可以在这里阅读更多关于它的内容:What are Class methods in Python for?

相关问题 更多 >