1

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

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

"some classes are running in a threaded environment" The .insert() method as written in the question is not thread-safe.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.