Reputation: 96
Suppose I have the following class inheriting from classes A
and B
:
class A:
def __init__(self):
self.x = 2
class B:
def __init__(self,u):
self.y = u + 2
class C(A,B):
def __init__(self):
#self.y should be 4 here
How do I initialize B only after initializing A? Using super(C,self).__init__()
doesn't let me use attributes of A into B.
Upvotes: 1
Views: 64
Reputation: 138
Just do this:
class A:
def __init__(self):
print("A was initialized")
self.x = 2
def getX(self):
return self.x
class B:
def __init__(self, u):
print("B was initialized")
self.u = u +2
class C(A,B):
def __init__(self, **kw):
A.__init__(self)
B.__init__(self, self.getX())
Upvotes: 1
Reputation: 7863
Alternatively, with super
:
class A:
def __init__(self):
self.x = 2
class B:
def __init__(self,u):
self.y = u + 2
class C(A,B):
def __init__(self):
super().__init__()
super(A, self).__init__(self.x)
Upvotes: 0
Reputation: 31
If you want to pass attributes in between classes use something like a return statement. Then in your B class use whatever the A class returned.
Upvotes: -1
Reputation: 54698
You don't HAVE to use super.
class A:
def __init__(self):
self.x = 2
class B:
def __init__(self,u):
self.y = u + 2
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self, self.x)
Now, that does mean some pretty tight coupling, in that C
has to be way too aware of what A.__init__
does.
Upvotes: 2