mercredi 23 novembre 2016

Python class __str__

My work-out: This is an assignment

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

My output:

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 execute the if part, this is OK the output get printed, now my error is person2 execute the if not the elif; how can I correct this

Aucun commentaire:

Enregistrer un commentaire