CannedSpinach CannedSpinach - 4 months ago 16
Python Question

Copying Attributes from Superclass Instance while Inheriting?

I'm trying to make a subclass that inherits from an instance of its superclass, and bases the majority of its attributes on the superclass attributes.

class Thing:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c

class ThingWithD(Thing):
def __init__(self, thing, d):
self.a = thing.a
self.b = thing.b
self.c = thing.c
self.d = d


Is there a more concise way to make the
a
,
b
, and
c
declarations inside
ThingWithD.__init__()
?

Answer

The most concise—and object-oriented—way would probably be to just call the superclass's __init__() method and avoid the repetition:

class Thing:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class ThingWithD(Thing):
    def __init__(self, thing, d):
        super(ThingWithD, self).__init__(thing.a, thing.b, thing.c)
        self.d = d
Comments