Python - When to create a Class and when to create a Function

此生再无相见时 提交于 2020-12-29 13:10:03

问题


Right, so I'm trying to create a Contacts application using Python OOP. I'm fairly new to OOP and still trying to get my head around the concepts.

I understand that a Class is a blueprint for all objects. I like to think of a Class as an entity and each Object is a record of that entity. I am from a Database background so that's why I interpret it like this, feel free to correct me.

Anyways, in the Contacts app I'm making I've created the Class Contacts as outlined below:

 class Contacts():
    def __init__(self, firstName, lastName, address, groupType,
                 telephone, mobile, email, photoField):
        self.firstName = firstName
        self.lastName = lastName
        self.address = address
        self.groupType = groupType
        self.telephone = telephone
        self.mobile = mobile
        self.email = email
        self.photoField = photoField

    def showDetails(self):
        print("First Name:\t", self.firstName)
        print("Last Name:\t", self.lastName)
        print("Address:\t", self.address)
        print("Telephone:\t", self.telephone)
        print("Mobile:\t", self.mobile)
        print("Email:\t", self.email)

Now, if I want to add contacts through the Contacts class into the list I'm using to store each contact object, do I have to create an AddContacts class, or do I create a function instead? I don't know if I'm putting my question across well enough for you to understand what I mean?

What I guess I'm trying to say is that adding contacts is a process and if you look at it from a database point of view you wouldn't create a table called "tbl_AddContacts" since you would do that via a query or a stored procedure, so in my view I would define adding contacts being a function. But asking my colleague who does C# programming he says that adding contacts should be defined by a Class.

This is a confusing concept for me, especially since I don't understand how I would link the AddContacts class with the Contacts class, or even how to define an AddContacts class in the first place!.

Here is the function I defined for adding contacts:

def addContacts():
    firstName = input("First Name: ")
    lastName = input("Last Name: ")
    address = input("Address: ")
    telephone = input("Telephone: ")
    mobile = input("Mobile: ")
    email = input("Email: ")
    print("\n")

    contact = Contacts(firstName, lastName, address, None, telephone, mobile, email, None)

    contactsList.append(contact)

    pickle.dump(contactsList, open("save.p", "wb"))

Please help me out, since I will turning this into a GUI application (uni assignment).


回答1:


Adding a contact is doing something, rather than being something, so it would make sense as a method/function rather than a class. I would suggest that your functionality should actually be in two separate places.

Creating a new contact from user input should be a class method of Contact:

class Contact(object):

    ...

    @classmethod
    def from_input(cls):
        firstName = input("First Name: ")
        lastName = input("Last Name: ")
        address = input("Address: ")
        telephone = input("Telephone: ")
        mobile = input("Mobile: ")
        email = input("Email: ")
        return cls(firstName, lastName, address, None, 
                   telephone, mobile, email, None)

Adding a new contact to the list of contacts should either be:

  1. An instance method of the e.g. AddressBook or ContactList class (or whatever you have holding the contact list); or
  2. A separate function if you don't have a class to hold the Contact instances.

For example:

class AddressBook(object):

    ...

    def add_contact(self, contact=None):
        if contact is None:
            contact = Contact.from_input()
        self.contacts.append(contact)

Now your UI can create a Contact and pass it straight to address_book.add_contact().




回答2:


First, your Contacts class is more appropriately called Contact, since it only represents a single contact. Your addContacts options can either be a standalone function, or you could make it part of a ContactList class, which manages your list of Contact objects.

class ContactList():
    def __int__(self):
        self.contact_list = []

    def addContact(firstName, lastName, address, telephone, mobile, email):
        contact = Contact(firstName, lastName, address, None, telephone, mobile, email, None)
        self.contact_list.append(contact)
        pickle.dump(contact_list, open("save.p", "wb"))

I would recommend separating the UI interaction piece (all the input() calls) from your function/method, because as you said, eventually this is going to become a GUI app. You should keep the code that's actually getting input from the user separated so you can change it later without having to change any part of Contact or ContactList.



来源:https://stackoverflow.com/questions/23831504/python-when-to-create-a-class-and-when-to-create-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!