Python类__str__

时间:2016-11-23 12:40:51

标签: python-2.7 class if-statement

我的工作:这是一项作业

class Person(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        if isinstance(person1, Lecturer):
            return "Name: " + self.name + "\tOccupation: " + self.occupation
        elif isinstance(person2, Student):
            return "Name: " + self.name + "\tStudent Number: " + self.studentNumber

class Lecturer(Person):
    def Occupation(self, occupation):
        self.occupation = occupation

class Student(Person):
    def StudentNumber(self, studentNumber):
        self.studentNumber = studentNumber

person1 = Lecturer("Elisha Nsemwa")
person2 = Student("Fabian Hamza")

person1.Occupation("Senior Lecturer")
person2.StudentNumber("HD5603")

print person1
print person2

我的输出:

Name: Elisha Nsemwa Occupation: Senior Lecturer

"assignment.py", line 26, in <module>
print person2

"assignment.py", line 7, in __str__
return "Name: " + self.name + "\tOccupation: " + self.occupation
AttributeError: 'Student' object has no attribute 'occupation'

person1执行if部分,这可以输出打印,现在我的错误是person2执行if if not elif;我怎样才能纠正这个

1 个答案:

答案 0 :(得分:1)

 def __str__(self):
    if isinstance(person1, Lecturer):
        return "Name: " + self.name + "\tOccupation: " + self.occupation
    elif isinstance(person2, Student):
        return "Name: " + self.name + "\tStudent Number: " + self.studentNumber

您正在测试person1person2,因此isinstance(person1, Lecturer)始终为true。您想知道的是self

的实例
...     def __str__(self):
...         if isinstance(self,  Lecturer):
...             return "Name: " + self.name + "\tOccupation: " + self.occupation
...         elif isinstance(self,Student):
...             return "Name: " + self.name + "\tStudent Number: " + self.studentNumber
...

...

>>> print person1
Name: Elisha Nsemwa     Occupation: Senior Lecturer
>>> print person2
Name: Fabian Hamza      Student Number: HD5603