That One Random Scrub That One Random Scrub - 2 months ago 8
Python Question

How can I add to the initial definition of a python class inheriting from another class?

I'm trying to define

self.data
inside a class inheriting from a class

class Object():
def __init__(self):
self.data="1234"

class New_Object(Object):
# Code changing self.data here


But I ran into an issue.

class Object():
def __init__(self):
self.data="1234"


So I have the beginning class here, which is imported from elsewhere, and let's say that the class is a universal one so I can't modify the original at all.

In the original, the instance is referred to as "
self
" inside the class, and it is defined as self inside the definition
__init__
.

class New_Object(Object):
# Code changing self.data here


So if I wanted to inherit from the class
Object
, but define self.data inside
New_Object
, I thought I would have to define
__init__
in
New_Object
, but this overrides the
__init__
from
New_Object


Is there any way I could do this without copypasting the
__init__
from
Object
?

Answer

You use super to call the original implementation.

class New_Object(Object):
    def __init__(self):
        super(NewObject, self).__init__()
        self.info = 'whatever'