如何让一个类在 Python 中继承其父级的值?

pyl*_*lab 0 python inheritance class

这是我想要做的事情的粗略想法:

class PlayerModel(Timeline):
    def __init__(self, name):
        self.name = name

        self.timeline_min = super(timeline_min)     # I don't know the syntax for this
        self.timeline_max = super(timeline_max)     # I don't know the syntax for this


class Timeline:
    def __init__(self):
        self.timeline_min = 0
        self.timeline_max = 120

    def make_model(self, m_name):
        return PlayerModel(m_name)
Run Code Online (Sandbox Code Playgroud)

我想PlayerModel拥有相同的属性Timeline

self.timeline_min = 0
self.timeline_max = 120
Run Code Online (Sandbox Code Playgroud)

在 it's 中__init__,而不必将它们作为参数传递。我可以使用super()? 我找不到用父变量来做到这一点的方法。

Ano*_*ous 5

您应该Timeline通过调用它来设置它们__init__

class PlayerModel(Timeline):
    def __init__(self, name):
        super().__init__()
        self.name = name
Run Code Online (Sandbox Code Playgroud)

除非您在子__init__方法中显式调用父构造函数,否则Python 只是假设您只想覆盖父构造函数。