Python __init__ Method In Inherited Class
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method
Solution 1:
As far as I know that's not possible, however you can call the init method of the superclass, like this:
classinheritedclass(initialclass):def__init__(self):
initialclass.__init__(self)
self.attr3 = 'three'
Solution 2:
Just call the parent's __init__
using super
:
classinheritedclass(initialclass):def__new__(self):
self.attr3 = 'three'super(initialclass, self).__init__()
I strongly advise to follow Python's naming conventions and start a class with a Capital letter, e.g. InheritedClass
and InitialClass
. This helps quickly distinguish classes from methods and variables.
Solution 3:
First of all you're mixing __init__
and __new__
, they are different things. __new__
doesn't take instance (self
) as argument, it takes class (cls
).
As for the main part of your question, what you have to do is use super
to invoke superclass' __init__
.
Your code should look like this:
classinitialclass(object):def__init__(self):
self.attr1 = 'one'self.attr2 = 'two'classinheritedclass(initialclass):def__init__(self):
self.attr3 = 'three'super(inheritedclass, self).__init__()
Solution 4:
Just call a designated method from the parent's init, if it exists:
classinitialclass():def__init__(self):
self.attr1 = 'one'self.attr2 = 'two'if hasattr(self, 'init_subclass'):
self.init_subclass()
classinheritedclass(initialclass):definit_subclass(self):
self.attr3 = 'three'
Solution 5:
classinitialclass:
def__init__(self):
self.attr1 = 'one'
self.attr2 = 'two'classinheritedclass(initialclass):
def__init__(self):
super().__init__()
self.attr3 = 'three'defsomemethod(self):
print (self.attr1, self.attr2, self.attr3)
a=inheritedclass()
a.somemethod()
1.List item
Post a Comment for "Python __init__ Method In Inherited Class"