Reputation: 357
I read some posts regarding how we can create a shared variable among class instances in python. One way to do it is to define this variable before class initialization. While this works for variables, it seems it doesn't work for what I want.
class C1:
def __init__(self, a, b):
self.c = a + b
class C2:
obj1 = C1(x,y)
def __init__(self):
self.d = 1
obj2 = C2
How can we set variables x and y for the instance obj1 of class C1? If we define this instance inside C2 initialization, then we could write
obj2 = C2(var1,var2)
But, now that it is outside C2 initialization, I don't know how to do it. Any idea?
Upvotes: 4
Views: 2810
Reputation: 1624
I am not sure if I am getting this right, what is wrong with this approach?
class C1:
def __init__(self, a, b):
self.c = a + b
x = 5
y = 3
class C2:
obj1 = C1(x,y)
def __init__(self):
self.d = 1
print(self.obj1.c)
obj2 = C2()
Another approach,
class C2:
obj1 = None
def __init__(self,ob):
self.d = 1
self.obj1 = ob
def show(self):
print(self.obj1.c)
x = 5
y = 3
obj1 = C1(x,y)
obj2 = C2(obj1)
obj2.show()
Upvotes: 3
Reputation: 2694
I think you should look at using classmethod
decorator. You have to call the class method once by class/instance object and variable will be shared across instances until further modified.
class C1:
def __init__(self, a, b):
self.c = a + b
class C2:
obj1 = None
def __init__(self):
self.d = 1
@classmethod
def class1(cls, x, y):
cls.obj1 = C1(x, y)
C2.class1(2, 3)
obj2 = C2()
print(obj2.obj1.c) # Output would be 5
obj22 = C2()
print(obj22.obj1.c) # Output would be same as above i.e 5
Hope it will help!
Upvotes: 2