Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add contents of a parent class method into a subclass method [duplicate]

Tags:

python

oop

Okay I'm new to OOP, and my problem is that I have this parent class and it has a method info in it.I want to reuse the two print statements within that method for its subclass inside a method of the same name and add more information to it. but I can't get it to work

class company:

    def __init__(self, fName, lName, salary):

        self.fName = fName
        self.lName = lName
        self.salary = salary

    def info(self):
        print("Name:", self.fName, self.lName)
        print("Salary:", self.salary)

class programmers(company):
    def __init__(self, fName, lName, salary, progLang):

        super().__init__(fName, lName, salary)
        self.progLang = progLang

    def info(self):
        print("Programming language:", self.progLang)

programmer1 = programmers("John", "Doe", 1000, "Python")
programmer1.info()

I thought of just rewriting the lines of code I want to reuse but I though that would take the point out of OOP.

I'm looking for this kind of output...

Name: John Doe
Salary: 1000
Programming language: Python

I'm using Python 3

Thanks in advance!

like image 534
Acubal Avatar asked Nov 09 '22 06:11

Acubal


1 Answers

Try out below code. Your parent class should inherit from "object". super only works for new style classes

class company(object):

    def __init__(self, fName, lName, salary):

        self.fName = fName
        self.lName = lName
        self.salary = salary

    def info(self):
        print("Name:", self.fName, self.lName)
        print("Salary:", self.salary)

class programmers(company):
    def __init__(self, fName, lName, salary, progLang):

        super(programmers, self).__init__(fName, lName, salary)
        self.progLang = progLang

    def info(self):
        super(programmers, self).info()
        print("Programming language:", self.progLang)

programmer1 = programmers("John", "Doe", 1000, "Python")
programmer1.info()
like image 96
Akshay Avatar answered Nov 14 '22 21:11

Akshay