【问题标题】:How do I print the actual contents of this list如何打印此列表的实际内容
【发布时间】:2011-07-18 01:31:12
【问题描述】:

代码短小精悍:

class Contact:
    all_contacts = []

    def __init__(self, name, email):
        self.name = name
        self.email = email
        Contact.all_contacts.append(self)


c1 = Contact("Paul", "something@hotmail.com")
c2 = Contact("Darren", "another_thing@hotmail.com")
c3 = Contact("Jennie", "different@hotmail.com")


for i in Contact.all_contacts:
    print(i)

显然,我想要做的就是打印带有我添加的信息的“all_contacts”列表,但我得到的是:

<__main__.Contact object at 0x2ccf70>
<__main__.Contact object at 0x2ccf90>
<__main__.Contact object at 0x2ccfd0>

我做错了什么?

【问题讨论】:

    标签: oop list python-3.x


    【解决方案1】:

    将以下内容添加到您的联系人类中:

    class Contact:
        ...
        def __str__(self):
            return '%s <%s>' % (self.name, self.email)
    

    这将告诉 Python 如何以人类可读的字符串表示形式呈现您的对象。

    Reference information for str

    【讨论】:

      【解决方案2】:

      Contact__repr____str__ 方法未定义,因此您将获得此默认字符串表示。

      def __str__(self):
          return '<Contact %s, %s>' % (self.name, self.email)
      

      【讨论】:

        【解决方案3】:
        1. 将容器与容器中存放的物品分开。

        2. __str__() 方法添加到Contact

          class Contact:
              def __init__(self, name, email):
                  self.name = name
                  self.email = email
              def __str__(self):
                  return "{} <{}>".format(self.name, self.email)
          
          class ContactList(list):
              def add_contact(self, *args):
                  self.append(Contact(*args))
          
          c = ContactList()
          c.add_contact("Paul", "something@hotmail.com")
          c.add_contact("Darren", "another_thing@hotmail.com")
          c.add_contact("Jennie", "different@hotmail.com")
          
          for i in c:
              print(i)
          

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-06
          • 1970-01-01
          • 1970-01-01
          • 2017-12-27
          • 2013-11-24
          • 2022-11-22
          相关资源
          最近更新 更多