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?
You use super to call the original implementation.
class New_Object(Object): def __init__(self): super(NewObject, self).__init__() self.info = 'whatever'
That's what super is for:
class NewObject(Object): def __init__(self): super(NewObject, self).__init__() # self.data exists now, and you can modify it if necessary
You can use super().__init__() to call Object.__init__() from New_Object.__init__().
What you would do:
class Object: def __init__(self): print("Object init") self.data = "1234" class New_Object(Object): def __init__(self): print("calling super") super().__init__() print("data is now", self.data) self.data = self.data.split("3") o = New_Object() # calling super # Object init # data is now 1234
Note that you do not have to give any arguments to super(), as long as you are using Python 3.
The answer is that you call the superclass's __init__ explicitly during the subclass's __init__. This can be done either of two ways:
Object.__init__(self) # requires you to name the superclass explicitly
super(NewObject, self).__init__() # requires you to name the subclass explicitly
The latter also requires you to ensure that you're using "new-style" classes: in Python 3 that's always the case, but in Python 2 you must be sure to inherit from the builtin object class. In Python 3 it can actually be expressed even more simply:
Personally, in most of my code the "disadvantage" of having to name the superclass explicitly is no disadvantage at all, and Object.__init__() lends transparency since it makes it absolutely clear what is being called. This is because most of my code is single-inheritance only. The super route comes into its own when you have multiple inheritance. See What does 'super' do in Python?
Python 2 example:
class Object(object): def __init__(self): self.data = "1234" class NewObject: def __init__(self): # subclass-specific stuff super(NewObject, self).__init__() # more subclass-specific stuff