Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a shared object among class instances in python?

Tags:

python

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?

like image 739
user491626 Avatar asked Oct 23 '25 18:10

user491626


2 Answers

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()
like image 63
Shivam Singh Avatar answered Oct 26 '25 11:10

Shivam Singh


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!

like image 43
MaNKuR Avatar answered Oct 26 '25 12:10

MaNKuR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!