【问题标题】:Can child classes inherit instance variables from their parent class in Python? [duplicate]子类可以从 Python 中的父类继承实例变量吗? [复制]
【发布时间】:2018-05-06 18:48:36
【问题描述】:

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

例如

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

除了在子类中重新声明名称和职业实例变量之外,这些可以通过其他方式继承吗?

【问题讨论】:

  • 通常你会调用超类init,通过使用`super()

标签: python python-2.7


【解决方案1】:

你应该从父类调用__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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    相关资源
    最近更新 更多