简体   繁体   中英

Getters/Setters for Python Class

So I am working on setting up a Python class that is to be used as a way to get/set parts of a dictionary. I'm trying to set it up so that I have a dictionary (for example ID Numbers : Names) and a variable that is the currently selected member of the dictionary.

I am trying to implement it so that I have getters and setters to return what the currently selected dictionary value is, as well as setters with a try/except block to change the current selection to another member in the dictionary. I don't care about passing the ID Number, I just need to make sure I can retrieve the Name through the getter. This is the code I have:

class Classroom:

    def __init__(self):

        self.__classList = {
            001: Mark,
            002: Kevin,
            003: Stacy}
        self.currentStudent = self.__classList[001] #start at the beginning of the list

    @property
    def currentStudent(self):
        return self.__currentStudent

    @currentStudent.setter
    def currentStudent(self, ID):
        try:
            currentStudent = __classList[ID]
        except:
            print("Invalid ID entered")

When I went to test the code, from my understanding with using @property if I input the following:

classroom = Classroom()
classroom.currentStudent = 002
print(classroom.currentStudent)

I should have the screen print "Kevin" no? What I am getting at the moment is the screen is printing 002. What am I doing wrong?

I have modified it a little bit to make it work. I suppose you are using python2.7

class ClassRoom(object):

    def __init__(self):

        self.__classList = {
            001: "Mark",
            002: "Kevin",
            003: "Stacy"}
        self.__currentStudent = self.__classList[001] #start at the beginning of the list

    @property
    def currentStudent(self):
        return self.__currentStudent

    @currentStudent.setter
    def currentStudent(self, ID):
        try:
            self.__currentStudent = self.__classList[ID]
        except:
            print("Invalid ID entered")

class_room_1 = ClassRoom()
class_room_1.currentStudent = 002

test

print class_room_1.currentStudent
Kevin

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