簡體   English   中英

如何在python中使用getter/setter方法來操作列表?

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

我只是想知道為什么我不能向班級中的方法發送值。 該程序的目標是使用 getter/setter 技術(不是 @property 技術)並按字母順序在我的 csv 文件中打印客戶端。 接下來,必須有另一種方法可以將客戶端添加到列表中並按字母順序保留列表。 我的困惑是如何在這些 get/set 方法中發送列表值以及如何更改它們以按順序排列我的文件數據:

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)      

您的代碼有一些問題。 使用 pylint 和編譯器錯誤將有助於確定哪些行有問題,讓您一次專注於一個問題。 我已經重寫了你的代碼作為我提到的一點的例子。

第一個問題是您的縮進似乎不正確(或者至少是粘貼到 SO 中的)。 Python 使用縮進來確定代碼塊的范圍。

其次,您有一個客戶端對象,其每個屬性都存儲了多個不同人的詳細信息。 更好的方法是為每個人設置一個客戶端對象。 這可以存儲在數組或其他結構中,以便於訪問。

第三,你的 getter 不需要參數,但你的 setter 需要(除了 self)。 setter 需要一個參數,因為該參數的值將設置為 objects 屬性。

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()

至於為什么應該使用 getter/setter,它們可以控制屬性的訪問和更新方式。 當您只需要讀取數據時,getter 可以阻止您意外更新屬性,而 setter 可以確保值正確。 對於setAge()您可以添加代碼將所有負數轉換為正數,這樣如果輸入-20 ,年齡實際上會保存為20

這個答案為使用 getter/setter 提供了其他很好的理由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM