如何使用super()从Parent类继承默认值

时间:2017-12-13 21:59:04

标签: python inheritance default init super

这里对python来说相当新,而且作为一般编程,我有以下示例,其中我尝试从父类继承默认值,以这两种对象都可以制作。 怎么做得很干净? - 尝试用* args和** kwargs进行实验,但它有不同的错误。

class Person(object):

def __init__(self, name="Jane Doe", age="30", gender="female"):
    self.name = name
    self.age = age
    self.gender = gender
    self.goal = "My goal is: Live for the moment!"


class Student(Person):

def __init__(self, name, age, gender, prev_org="The School of Life", skip_d=0):
    super(Student, self).__init__(name, age, gender,)
    self.prev_org = prev_org
    self.skip_d = skip_d
    self.goal = "Be a junior software developer."

 john = Student('John Doe', 20, 'male', 'BME')

 student = Student()

2 个答案:

答案 0 :(得分:0)

我不认为这是可能的。我所看到的是这样的事情:

class Person(object):

    def __init__(self, name=None, age=None, gender=None):
        if name is None:
            name = "Jane Doe"
        if age is None:
            age = "30"
        if gender is None:
            gender = "female"

        self.name = name
        self.age = age
        self.gender = gender
        self.goal = "My goal is: Live for the moment!"


class Student(Person):

    def __init__(self, name=None, age=None, gender=None, prev_org="The School of Life", skip_d=0):
        super(Student, self).__init__(name, age, gender)
        self.prev_org = prev_org
        self.skip_d = skip_d
        self.goal = "Be a junior software developer."


john = Student('John Doe', 20, 'male', 'BME')

student = Student()

答案 1 :(得分:0)

您可以使用*args实现这一目标,但我认为这不是一个很棒的设计选择。

class Student(Person):

    def __init__(self, *args, prev_org="The School of Life", skip_d=0):
        super(Student, self).__init__(*args[:2])

这是将前3个位置参数传递给父(Person)类,因此Student并不需要担心它。

您需要对列表进行切片([:2]),因为如果您像这样创建Student的实例:

john = Student('John Doe', 20, 'male', 'BME')

然后'BME'现在是位置参数,并包含在*args中。鉴于:

john = Student('John Doe', 20, 'male', prev_org='BME')

现在它是一个关键字参数,因此不会出现在*args中。