所以我正在设置一个Python类,用作获取/设置字典部分的方法。我试图设置它以便我有一个字典(例如ID Numbers:Names)和一个变量,它是当前选定的字典成员。
我正在尝试实现它,以便我有getter和setter来返回当前选择的字典值,以及带有try / except块的setter将当前选择更改为字典中的另一个成员。我不在乎传递ID号,我只需要确保我可以通过getter检索Name。这是我的代码:
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)
我应该有丝网印刷" Kevin"没有?我现在得到的是屏幕正在打印002.我做错了什么?
答案 0 :(得分: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