2017-07-19 27 views
2

我正在學習和嘗試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) 
+0

print_contacts(Contact.contact_list),Python中的註釋都打上了''#'不'//,你也需要標記的第二功能作爲一個類方法或任一因素出來 – arielnmz

+0

__init__方法不返回任何有意義的值。所以基本上你應該做'Contact.contact_list.append(self)',因爲'return'沒有任何用處。而且,list.append()不會返回任何東西...... –

回答

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", "[email protected]") 
cont2 = Contact("Mary", "[email protected]") 
Contact.print_contacts() 

將打印

>>John 
    Mary 

要回答你的問題,爲什麼你的代碼目前不工作:第一,你的的init方法不需要回電話,init被調用來創建對象來建立對象變量,並且通常不需要返回任何東西(特別是在這種情況下,因爲.append()不提供任何返回值)。其次,類方法似乎更適合你正在嘗試用第二個方法做,你可以閱讀更多有關在這裏:What are Class methods in Python for?

+0

'@ classmethod'將類作爲第一個參數。您可能想提供一個完整的例子,說明您的意圖與該建議有何關係。 – salparadise

+2

如果您使用'print_contacts'作爲類方法,則應該更乾淨地實現它。 'def print_contacts(cls):在cls.contact_list中聯繫:print(contact.name)' –

+0

好的提示,亞當。謝謝。 – SeeDerekEngineer

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", "[email protected]") 
contacts.append(adam) 

bob = Contact("Bob Jones", "[email protected]") 
contacts.append(bob) 

charlie = Contact("Charlie Doe", "[email protected]") 
contacts.append(charlie) 

print_contacts(contacts) 
# Adam Smith <[email protected]> 
# Bob Jones <[email protected]> 
# Charlie Doe <[email protected]> 

或者,模型的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", "[email protected]") 
contacts.add_contact("Bob Jones", "[email protected]") 
contacts.add_contact("Charlie Doe", "[email protected]") 
contacts.display_contacts() 
+0

只是爲了好玩[在haskell](https://repl.it/J9iy) –