This question already has answers here:
How do I call a parent class's method from a child class in Python?

(15个答案)


4年前关闭。




好的,我是OOP的新手,我的问题是我有这个父类,并且里面有一个方法信息,我想在同名方法中为其子类重用该方法中的两个print语句并添加向它提供更多信息。但我无法正常工作
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()

我想到的只是重写要重用的代码行,但是尽管如此,我仍然可以将其从OOP中删除。

我正在寻找这种输出...
Name: John Doe
Salary: 1000
Programming language: Python

我正在使用Python 3

提前致谢!

最佳答案

试试下面的代码。您的父类应继承自"object"。 super仅适用于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()

关于python - 如何将父类方法的内容添加到子类方法中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40325509/

10-11 22:53
查看更多