首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python 3编写的小地址簿

用Python 3编写的小地址簿
EN

Code Review用户
提问于 2018-11-02 14:27:23
回答 1查看 5.2K关注 0票数 3

到目前为止,这个程序似乎运行得很好,但我知道它可以使用某些功能/方法更干净、效率更高。由于我还在开始编写代码,任何反馈都是非常欢迎的。

代码语言:javascript
复制
# Creating class named contacts with methods for editing and adding new 
# contacts. Also there are static methods for showing a specific or all
# contacts data and for showing if there's no contact saved on the address book.

class Contact:

    def __init__(self, name, surname, number, email):
        self.name = name
        self.surname = surname
        self.number = number
        self.email = email

    def edit_name(self, name):
        self.name = name
        return self.name

    def edit_surname(self, surname):
        self.surname = surname
        return self.surname

    def edit_number(self, number):
        self.number = number
        return self.number

    def edit_email(self, email):
        self.email = email
        return self.email

    @classmethod
    def add(cls, name, surname, number, email):
        return cls(name, surname, number, email)

    # This method prints prints all data of a specific entry it index is provided
    # otherwise it prints data of all entries saved in address book (fullnames, 
    # numbers and emails)
    @staticmethod
    def summary(index=0):
        if index == 0:
            for j in range(0, len(address_book)):
                print(address_book[j].name, address_book[j].surname, end=' / ')
                print(address_book[j].number, '/', address_book[j].email)
        else:
            print(address_book[index].name, address_book[index].surname, end=' / ')
            print(address_book[index].number, '/', address_book[index].email)
        print()
        return None

    # Prints only the names saved in the address book
    @staticmethod
    def saved():
        print('CONTACTS SAVED: ', end='')
        for j in range(0, len(address_book)):
            print(j, address_book[j].name, end=' || ')
        return None

    # Prompts the user if there's no contact saved in address book
    @staticmethod
    def isempty(list):
        if len(list) == 0:
            print('NO CONTACT SAVED\n')
            return True
        return False

该程序现在提示用户选择从0到5的范围.每个选项在地址簿中都有一个功能:添加、修改、删除、查看、查看所有、完成。

代码语言:javascript
复制
address_book = []
msg_error = '{}Invalid option{}'.format('\033[31m', '\033[m'    # Red text

access = input('Press any key to access')

while True:
    print('=-=-===-=-=-=-=-  CONTACTS MENU -=-=-=-=-=-==-==')
    print("""[ 1 ] ADD    [ 3 ] DELETE     [ 5 ] VIEW ALL
[ 2 ] MODIFY    [ 4 ] VIEW   [ 0 ] FINISH""")

  option = input('>>> ')

  #This if and elif blocks check if user input ranges from 0-5
  if not option.isnumeric():
      print(msg_error)
      continue

  elif option not in '012345':
      print(msg_error)
      continue

  # If between 0-5, convert value to integer and...
  else:
      option = int(option)

  if option == 0:
      print('>>> Program ended\n')
      break

  # Add new contact
  elif option == 1:
      name = input('Name: ').capitalize().strip()
      surname = input('Surname: ').capitalize().strip()
      number = input('Number: ').strip()
      email = input('Email: ').strip().lower()

      # Trasnform into Contact class and append to address book
      address_book.append(Contact.add(name, surname, number, email))
      print('Contact saved\n')

  # Modify a contact
  elif option == 2:
      if Contact.isempty(address_book):
          continue

      Contact.saved()
      name_index = int(input('\nModify which name? '))
      print('\nModify which entry?')
      entry_index = int(input('[ 1 ] NAME   [ 2 ] SURNAME   [ 3 ] NUMBER   [ 4 ] EMAIL\n>>>'))

      # Use object methods to modify within the list address book
      # User wants to modify name
      if entry_index == 1:
          modification = input('New name: ').capitalize().strip()
          address_book[name_index].edit_name(modification)

      # User wants to modify surname
      elif entry_index == 2:
          modification = input('New surname: ').capitalize().strip()
          address_book[name_index].edit_surname(modification)

      # User wants to modify number
      elif entry_index == 3:
          modification = input('New number: ').strip()
          address_book[name_index].edit_number(modification)

      # User wants to modify email
      elif entry_index == 4:
          modification = input('New email: ').lower().strip()
          address_book[name_index].edit_email(modification)
      print('Modification saved\n')

  # Delete a contact
  elif option == 3:
      if Contact.isempty(address_book):
          continue

      Contact.saved()
      name_index = int(input('\nWhich contact delete? '))
      del address_book[name_index]
      print('Contact deleted')

  # View specific contact details
  elif option == 4:
      if Contact.isempty(address_book):
          continue

      Contact.saved()
      index = int(input('\nContact position: '))
      Contact.summary(index)

  # View details of all contacts
  elif option == 5:
      if Contact.isempty(address_book):
          continue
      Contact.summary()
EN

回答 1

Code Review用户

发布于 2018-11-02 15:25:12

您正在以一种奇怪的方式使用Python类。

  • 首先,如果您想创建一个新的Contact实例,只需调用Contact(name, surname, number, email)即可。不需要Contact.add,因为它做的事情完全一样。
  • 接下来,您所有的静态方法。它们(几乎)与对象Contact无关,它们都操作一个联系人列表,即通讯簿。这意味着您可以使它们成为在该列表上操作的函数/内联代码,或者创建一个处理它的AddressBook类。在这种情况下,我可能会选择第一个选择。如果Contact.isempty(address_book):继续成为如果不是address_book: print(‘没有联系人保存\n’),继续,这使用的事实是,空列表是虚假的。Contact.saved变成print(‘contact SAVED:’',end=''),对于j,contact in枚举(Address_book):print(j,contact.name,end=‘),其中迭代可迭代而不是迭代索引。您可以(也可能应该)将其放入函数中: def print_address_book(address_book):print(“联系人保存:”,end=“”)表示j,联系人在枚举中(Address_book):print(j,contact.name,end=‘去处“)
  • 不需要所有的Contact.edit_*方法。在Python中,您通常希望避免生成getter和setter,而是使用裸属性,除非您真的必须这样做。你已经有了它们是正常的属性,所以你可以直接修改它们。但在我们这样做之前,允许字典(如访问这些条目)可能是有意义的,因此您可以使用contact["name"]而不是contact.name:class Contact:.def __getitem__(self,key):返回getattr(self,key) def __setitem__(self,key,value):setattr(self,key,value) --这使得更新联系人变得更加容易: name_index =int(输入(‘\nModify,哪个名称?’)而name_index不在范围(len(Address_book)):name_index =int(输入(‘\n nModify,哪个名称?'))打印(‘\n修改哪个条目?’)EMAIL\n>>>=.lower().lower(),而不输入{“名称”、“姓氏”、“数字”、“电子邮件”}:.lower(‘姓名、姓氏、号码、EMAIL\n>>> ') .lower() address_book名字_索引 = input('New:’) print('Modification \n‘)i还添加了一些代码,以确保用户输入合理的输入。
  • 选择0意味着打印Contact.summary中的所有联系人(这也不应该是一种静态方法,而是一个独立的AddressBook函数或方法)不是一个好主意。这意味着您不能打印第一个联系人(请记住,Python从零开始计数)。使用-1 (有时在C/C++中这样做)作为打印所有条目的标志也是个坏主意,因为这样您就无法打印最后一个联系人(不调用len)。相反,只需使用None:try: index =int(输入(‘\n contact位置:’),除了ValueError: index = None print_summary(address_book,index) def print_summary(address_book,index=None):如果索引为None: contact in address_book: print(contact) index : print(address_book索引) print(),如您所见,我取消了您的显式打印,相反,让它成为Contact类的一部分,当被打印时,它看起来很漂亮。为此,您可以使用神奇的方法__str__,它应该返回实例的字符串表示:类联系人:.def __str__(self):返回“/ ".join(Self.name,self.surname,self.number,self.email)
  • 这个方法(以及__getitem____setitem__)是一个神奇的(或and )方法。在这里查看可以定义哪些其他特殊方法来提供自定义类的内置行为:https://rszalski.github.io/magicmethods/
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/206801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档