Reputation: 57
My problem is how to share a variable or a buffer between more than one class e.g. writing into a single buffer from multiple classes knowing that some classes are running in a threaded environment example
class my1(object):
def __init__(self):
self.buffer=[0]*5
self.size=0
def insert(self,data):
self.data=data
self.buffer[self.size]=self.data
self.size+=1
class my2(my1):
def __init__(self):
self.insert('data1')
class my3(my1):
def __init__(self):
self.insert('data2')
The desired result would be the buffer containing both data1 and data2 to be processed yet the buffer within class my1 is defined inside the (init) section and cannot be shared any suggestions? Thanks alot
Upvotes: 1
Views: 2271
Reputation: 28268
If you really want the buffer to be bound to the My1
class, you can use a static class variable
class My1(object):
buffer = [0] * 5
Upvotes: 0
Reputation: 2651
You're doing it wrong.
Just create an object of class my1
and pass it to objects of class my2
and my3
.
# leave my1 as it is
class my2(): # no need to inherit from my1
def __init__(self, my1obj): # buffer is object of my1
my1obj.insert('data1')
class my3():
def __init__(self, my1obj):
my1obj.insert('data2')
mybuffer = my1()
my2obj = my2(mybuffer)
my3obj = my3(mybuffer)
Upvotes: 1