Developer
Developer

Reputation: 178

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

Upvotes: 1

Views: 156

Answers (1)

fredtantini
fredtantini

Reputation: 16556

In

 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

you are testing person1 and person2, so isinstance(person1, Lecturer) is always true. What you want to know is the instance of 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

Upvotes: 1

Related Questions