子类可以从Python的父类继承实例变量吗?

时间:2017-11-22 22:19:06

标签: python python-2.7

在Python 2.7中,实例变量是否需要在子类中手动定义,还是可以直接从父类继承?

E.g。

class Person(object):
    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

class Teacher(Person):
    def __init__(self, name, occupation, subject):
        self.name = name
        self.occupation = occupation
        self.subject = subject

不是在子类中重新声明名称和占用实例变量,而是可以用另一种方式继承它们吗?

1 个答案:

答案 0 :(得分:3)

您应该从父类调用__init__

class Person(object):
    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

class Teacher(Person):
    def __init__(self, name, occupation, subject):
        Person.__init__(self, name, occupation)
        self.subject = subject