Reputation: 187
In this situation class A is a parent of classes B and C. The goal is to share state between the instances b and c. It's not about adding or overriding functions, but about the state value a
.
class A():
def __init__(self):
self.a ='a'
print('@a')
class B(A):
def __init__(self):
A.__init__(self)
self.x = 'b'
class C(A):
def __init__(self):
A.__init__(self)
self.x = 'c'
b = B()
c = C()
print(b.a, b.x)
print(c.a, c.x)
The output is
@a
@a
a b
a c
I understand why this is happening; __init__()
in A is being called twice. I could put a test in so it only sets the initial value once, but that does not seem to be a very elegant solution. Additionally it only allows one instance of A to be shared. If I want another instance of A to be shared between two other instance of B and C it can't be done. The same goes for making a
global inside the module and getting rid of class A entirely. Is there a good Pythonic way to solve this provlem?
Upvotes: 1
Views: 2036
Reputation: 281958
Agreeing with abarnert: this doesn't make any sense. This isn't what inheritance means.
Inheritance means that every B instance is an A instance, and every C instance is an A instance. A B instance doesn't have a separate A instance, and it certainly can't share with a C instance.
If you want B and C objects to have an A instance, and to have the same A instance, then you need composition:
class A(object):
def __init__(self):
self.state = whatever()
self.other_state = more_stuff()
class B(object):
def __init__(self, a):
self.a = a
class C(object):
def __init__(self, a):
self.a = a
a = A()
b = B(a)
c = C(a)
Now b
and c
are both sharing a single instance of A
, and changes to that shared instance will be visible through both objects.
Upvotes: 1