[Tutor] __str__ on a subclass

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jun 19 18:27:38 EDT 2017


On 19/06/17 20:32, Evuraan wrote:

> class Employee:
>         """Class with FirstName, LastName, Salary"""
>         def __init__(self, FirstName,LastName, Salary):
>         def __str__(self):
>                 return '("{}" "{}" "{}")'.format(self.FirstName,
>                                                  self.LastName, 
                                                   self.Salary)

> class Developer(Employee):
>         """Define a subclass, augment with ProgLang"""
>         def __init__(self, FirstName,LastName, Salary, ProgLang):
>                 Employee.__init__(self, FirstName,LastName, Salary)
>                 self.ProgLang = ProgLang
>         def dev_repr(self):
>                 return '("{}" "{}" "{}" "{}")'.format(self.FirstName,
>                                                       self.LastName, 
                                                        self.Salary,
                                                   self.ProgLang)

> a = Employee("Abigail", "Buchard", 83000)
> print(a)
> dev_1 = Developer("Samson", "Sue", 63000, "Cobol",)
> print(dev_1)
> print(dev_1.dev_repr())
> 
> running that yields,
> 
> ("Abigail" "Buchard" "83000")
> ("Samson" "Sue" "63000")
> ("Samson" "Sue" "63000" "Cobol")
> 
> My doubt is, how can we set the  __str__ method work on the Employee
> subclass so that it would show ProgLang too, like the
> print(dev_1.dev_repr())?

You  can't show ProgLang in Employee because it doesn't exist.
You can only show it on Developer. To make __str__() work for
developer you need to define it as you did for Employee.
You could just call self.dev_repr()

Or you could call super.__str__() and append self.ProgLang.
eg.

return super().__str__() + " " + self.ProgLang


Does that answer you question?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list