简体   繁体   中英

How can the getter/setter method be used in python to manipulate a list?

I'm just wondering why I cannot send values to methods in my class. The goal of the program is to use the getter/setter technique (not the @property one) and print clients in my csv file in alphabetical order. Next, there's gotta be another method that can add a client into the list and keep the list in alphabetical order. My confusion is how do I send the list values in these get/set methods and how would they be altered to put my file data in order:

L = []
F = []
G = []
A = []

class client ():
'''
A client class starts here to keep all the related ideas together.
Since we are more focused on object-orientied programming, it is
important that the code stays organized. A class will keep all related
objects together, making the code easier to understand from an outsider
perspective
'''

fh = open('client.csv', 'r')

#For loop is created to sift through each line obtaining each client's data
for line in fh:

    '''
    After numerous errors, I learned that a file object does not
    contain a 'split'property. In this next bit of code, each
    type of data is appended to the empty list and each line (which
    is a string object) is split by commas.
    '''

    L.append(line.split(",")[0].lstrip(""))
    F.append(line.split(",")[1])
    G.append(line.split(",")[2])
    A.append(line.split(",")[3].rstrip("\n"))

    '''
    The the square brackets contain the index of each data in each
    line; L has [0] since the last name is the first word in the
    csv file. Additionally it can be noticed that 'lstrip' and
    'rstrip' methods were used. These methods were used to eliminate any
    unnecessary characters that were printed with the output
    '''

def __init__(self, L, F, G, A):
    self.F = F
    self.L = L
    self.G = G
    self.A = A
    '''
    Constructing function allows arguments to be
    passed (automatically) onto any code outside the
    class.
    '''


def __del__(self):
    pass
    '''
    This function will act as the destructor, and so
    the file will destruct on its own when
    '''

def setFname(self):
    self.__F = Fname


def getFname(self, F):
    return self.__Fname

def setLname(self):
    self.__L = Lname

def getLname(self, L):
    return self.__Lname

def setGender(self):
    self.__G = Gender

def getGender(self, G):
    return self.__Gender

def setAge(self):
    self.__A = Age

def getAge(self, A):
    return self.__Age

def AddClient (L, F, G, A):
    '''
    This method will be used to add more clients to the list of
    existing clients. Their information is appended into the
    existing lists 
    '''
    print ('You may add a client to the directory here: ')
    print ('You will need to enter key infortaion about the client')
    NewLastName = input('Please enter their last name: ')
    L.append(NewLastName)
    NewFirstName = input ('Please enter their first name: ')
    F.append(NewFirstName)
    NewGender = input ('Please enter their gender (m/f): ')
    G.append(NewGender)
    NewAge = input ('Please enter their age: ')
    A.append(NewAge)

def RemoveClient (F, L):
    print ('You may remove a client from the directory here: ')
    print ('You will need to enter key information about the client')
    RemoveFirstName = input('Please enter their first name: ')
    RemoveLastName = input('Please enter their last name: ')
    L.clear(RemoveLastName)
    F.clear(RemoveFirstName)

C = client(L, F, G, A)      

You've got a few issues with your code. Using pylint and compiler error will help determine what lines are problematic, allowing you to focus on one issue at a time. I have rewritten your code as an example for the point I mentioned.

The first issue is that your indentation seems to be incorrect (or at least what was pasted into SO). Python uses indentation to determine the scope of blocks of code.

Secondly, you have a single client object with each of its properties storing the details of multiple different people. A better approach would be to have a single client object for each person. This can be stored in an array or other structure to make accessing it easier.

Third, your getters don't need an argument but your setters do (in addition to self). The setters need an argument as the value of that argument will be set to the objects property.

class client():
    '''
    A client class starts here to keep all the related ideas together.
    Since we are more focused on object-orientied programming, it is
    important that the code stays organized. A class will keep all
    related objects together, making the code easier to understand
    from an outsider perspective
    '''

    def __init__(self, L, F, G, A):
        '''
        This is the constructor, it will assign the supplied arguments to
        the parameters, initializing the object
        '''
        self.F = F
        self.L = L
        self.G = G
        self.A = A

    def setFname(self, Fname):
        self.F = Fname

    def getFname(self):
        return self.F

    def setLname(self, Lname):
        self.L = Lname

    def getLname(self):
        return self.L

    def setGender(self, Gender):
        self.G = Gender

    def getGender(self):
        return self.G

    def setAge(self, Age):
        self.A = Age

    def getAge(self):
        return self.A

def addClient():
    '''
    This method will be used to add more clients to the list of
    existing clients. Their information is appended into the
    existing lists
    '''
    print('Adding a new client.')
    lName = input('    Please enter their last name: ')
    fName = input('    Please enter their first name: ')
    gender = input('    Please enter their gender (m/f): ')
    age = input('    Please enter their age: ')

    allClients.append(client(lName, fName, gender, age))

allClients = []

def main():

    fh = open('client.csv', 'r')

    for line in fh:

        '''
        Iterate through each line of the file, getting the values out and
        creating a new client object with them
        '''

        lName = line.split(",")[0].lstrip("")
        fName = line.split(",")[1]
        gender = line.split(",")[2]
        age = line.split(",")[3].rstrip("\n")

        allClients.append(client(lName, fName, gender, age))

    # Call the add client function to demonstrate it
    addClient()

    # Print out each client
    for aClient in allClients:
        print("L:{}, F:{}, G:{}, A:{}".format(aClient.getLname(),
                                              aClient.getFname(),
                                              aClient.getGender(),
                                              aClient.getAge()))

if __name__== "__main__":
  main()

As for why you should be using getter/setters, they can control how properties are accessed and updated. Getters can stop you from accidentally updating properties when you only need to read the data, whereas setters can ensure the values are correct. For setAge() you could add code to convert all negative numbers to positive so that if -20 was entered, the age would actually be saved as 20 .

This answer provides other good reasons for using getters/setters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM