我的工作:这是一项作业
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;我怎样才能纠正这个
答案 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
您正在测试person1
和person2
,因此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