理解继承

时间:2017-08-05 03:12:46

标签: python inheritance

我试图更好地理解继承。在以下代码中,当我尝试打印friend.salary时,它会抛出AttributeError。没有WorkingStudent继承Student类的所有方法吗?

class Student:
    def __init__(self,name,school):
        self.name = name
        self.school = school
        self.marks = []

    def average(self):
        return sum(self.marks)/len(self.marks)

    def friend(self,friend_name):
        return Student(friend_name, self.school)

anna = Student("Anna","MIT")
friend = anna.friend("Motilal")
#print (friend.name)
#print (friend.school)

class WorkingStudent(Student):
    def __init__(self,name,school,salary):
        super().__init__(self,name,school)
        self.salary = salary
        anna = WorkingStudent("Anna","SXS",25000)
anna.friend("Greg")
anna.marks.append(50)
print friend.salary 

1 个答案:

答案 0 :(得分:0)

您应该修改源代码,如下所示

class Student:
    def __init__(self,name,school):
        self.name = name
        self.school = school
        self.marks = []

    def average(self):
        return sum(self.marks)/len(self.marks)

    def friend(self,friend_name):
        return Student(friend_name, self.school)


anna = Student("Anna","MIT")
friend = anna.friend("Motilal")
#print (friend.name)
#print (friend.school)


class WorkingStudent(Student):
    def __init__(self,name,school,salary):
        super(WorkingStudent,self).__init__(name,school)
        self.salary = salary
        # anna = WorkingStudent("Anna","SXS",25000)
    def friend(self,friend_name):
        return WorkingStudent(friend_name, self.school, self.salary)

# You should put your code here, because as your original code
# anna is an instance of Student not WorkingStudent class
# so it and its friend don't have "salary".
anna = WorkingStudent("Anna","SXS",25000) # After this line, anna is a different variable to "anna" variable that was defined before (anna = Student("Anna","MIT"))
friend = anna.friend("Greg") # friend now is an instance of WorkingStudent class, so it have salary
anna.marks.append(50)
print(friend.salary)

Editted。所以代码现在可以正常工作