如何使用字典更简单地调用属性

时间:2016-07-12 11:50:14

标签: python dictionary inheritance

我正在python中探索组合(has-a relationship)逻辑,为此我有一个Student的类Address。我试图通过在Student内使用student_dict来存储多个学生记录。我有GraduateStudent subclass ing Student。我使用字典并将id设置为键,并将相应的详细信息(例如姓名,年龄,部门)存储为值。稍后,如果我尝试添加学生地址,则在尝试访问它们时会变得复杂。示例:student_dict.get(id)[1])[2]

我的问题是在添加地址时,我会将其附加到学生的现有详细信息中。这会将地址添加为元组,并且在访问它时使用其他索引进行获取变得繁琐。您可以在add_address()中的Student方法和get_course()中的GraduateStudent方法中引用此方法。下面是代码和调用。有人可以通过一些方式来建议我可以轻松访问值而不是多维索引吗?

class Address(object):

    def __init__(self, street, pin):
        self.street = street
        self.pin = pin

    def __str__(self):
        return "Address: {} {}".format(self.street, self.pin)

class Student(object):    
    # Composition
    student_dict = {}

    def add_address(self, id, street, pin):
        self.address = Address(street, pin)
        self.student_dict[id] = self.student_dict[id], self.address

    def get_address(self, id):
        if (self.is_exists(id)):
            return self.get(id)[1]
        else:
            print "<No Student record found>"
            return ""

    def put(self, id, details):
        if id in self.student_dict.keys():
            print "Student %d already exists" %id
            return
        self.student_dict[id] = details

    ...

# class

# Class that extends Student
class GraduateStudent(Student):

    def put(self, id, *args):
        super(GraduateStudent, self).put(id, args)
    # def

    def get_course(self, id):
        if (self.is_exists(id)):
            return (self.get(id)[0])[2]
        else:
            print "<No record found>"
            return ""
    # def

# class 

调用次数:

s = GraduateStudent()
s.put(1, "Swad", 17, "Computer Science")
s.put(2, "Vish", 18, "MECH.")
s.put(3, "Vino", 18, "MECH.")

s.add_address(1, "11 vvk street", 600015)
s.add_address(2, "22 vvk street", 600015)
s.add_address(3, "33 vvk street", 600015)

print "\nStudent details::"
print 1,": COURSE: ", s.get_course(1), ",", s.get_address(1)
print 2,": COURSE: ", s.get_course(2), ",", s.get_address(2)
print 3,": COURSE: ", s.get_course(3), ",", s.get_address(3)

结果:

Student details::
1 : COURSE:  Computer Science , Address: 11 vvk street 600015
2 : COURSE:  MECH. , Address: 22 vvk street 600015
3 : COURSE:  MECH. , Address: 33 vvk street 600015    

1 个答案:

答案 0 :(得分:2)

只需将Student和GraduateStudent类的详细信息定义为属性即可。通过定义类属性studentid

,每个实例都可以具有唯一ID
class Student(object):   
    studentid = -1 
    def __init__(self, name, dob):
        Student.studentid += 1
        self.id = Student.studentid
        self.details = dict()
        self.name = name
        # Date of birth more useful than age :)
        self.dob = dob
        self.address = ""

    def add_address(self, street, pin):
        self.address = Address(street, pin)

    def get_address(self):
        return self.address

    def __str__(self):
        return "{}: Name {}, Address: {}".format(self.id, self.name, self.address)

class GraduateStudent(Student):
    def __init__(self, name, dob, course):
        super(GraduateStudent, self).__init__(name, dob)
        self.course = course
    def __str__(self):
        return "{}: Name: {}, Course: {}, Address: {}".format(self.id, self.name, self.course, self.address)

要跟踪学生列表,您可以定义一个Directory类,您可以在其中添加学生:

class Directory(object):
    def __init__(self):
        self.student_dict = dict()

    def add_student(self, student):
        if student.id in self.student_dict:
            print "Student %d already exists" % student.id
            return
        self.student_dict[student.id] = student
        return student.id

    def get_student(self, id):
        try:
            return self.student_dict[id]
        except KeyError:
            print "<No Student record found: %d>" % id
            return None

    def add_address(self, id, street, pin):
        student = self.get_student(id)
        if student is not None:
            student.add_address(street, pin)

    def get_address(self, id):
        student = self.get_student(id)
        if student is not None:
            return student.get_address()

    def print_students(self):
        for student in self.student_dict.values():
            print student

现在要操纵学生列表,你可以写:

>>> d = Directory()
>>> id1 = d.add_student(GraduateStudent('Swad', 1999, 'Computer Science'))
>>> id2 = d.add_student(GraduateStudent('Vish', 1998, 'MECH.'))
>>> id3 = d.add_student(GraduateStudent('Vino', 1998,  'MECH.'))
>>> d.add_address(id1, "11 vvk street", 600015)
>>> d.add_address(id2, "22 vvk street", 600015)
>>> d.add_address(id3, "33 vvk street", 600015)
>>> d.print_students()
0: Name: Swad, Course: Computer Science, Address: Address: 11 vvk street 600015
1: Name: Vish, Course: MECH., Address: Address: 22 vvk street 600015
2: Name: Vino, Course: MECH., Address: Address: 33 vvk street 600015