2017-06-19 64 views
1

因此,我正在設置一個Python類,用於獲取/設置字典的各個部分。我正在設置它,以便我有一本字典(例如ID號碼:名稱)和一個變量,它是當前選定的字典成員。Python的獲取者/設置者

我試圖實現它,以便讓getters和setter返回當前選定的字典值,以及具有try/except塊的setter將當前選擇更改爲字典中的另一個成員。我不在乎傳遞身份證號碼,我只需要確保我可以通過getter獲取姓名。這是我的代碼:

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

當我去測試代碼,從我的理解與使用@property如果我輸入以下內容:

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

我應該有絲網印刷「凱文「不?目前我得到的是屏幕正在打印002.我做錯了什麼?

+1

你沒有做Classroom'的'一個實例。你正在使用類對象本身,它的行爲非常不同。 – user2357112

+1

另外,你的二傳手無論如何都會被打斷。 – user2357112

+0

'currentStudent = __classList [ID]'< - 你應該從哪裏得到'__classList'?它不會工作,除非你在全局命名空間中有它...此外,鑑於你沒有把它存儲在任何地方,你可能會刪除該方法。 – zwer

回答

0

我已經修改它一點點,使其工作。我假設你正在使用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 

測試

print class_room_1.currentStudent 
Kevin 
+0

使'class_room_1.currentStudent == class_room_1.currentStudent'爲'False'似乎令人困惑。 – Blender