Python 在线程之间共享 class 实例数据和方法,但一个特定变量

In Python sharing class instance data and methods between threads but one specific variable

有一个已初始化的 class 实例,我需要在线程之间共享所有此实例数据和方法,但只有一个变量,以便在所有线程之间获得不同的结果,但要利用已初始化的数据。我需要实例中所有 class 方法指向那个 'private' 变量。

class A():

    def __init__(self):
        self.init_data = self._initialize()   <- same for each thread
        self.a = 0   <- private for each thread 

    def _initialize(self):
        # Get data from db (high cost)

    def calculate_a(self, data):
        # Calculate 'a' result from init_data to private 'a' variable

class ThreadClass(threading.Thread):

    # Inheritance? 
    # Pass instance as a init parameter and change somehow 'a' variable pointer? 


a = A()
t1 = ThreadClass(a)
t2 = ThreadClass(a)
t1.start()
t2.start()
t1.calculate_a(data1)
t2.calculate_a(data2)
t1.a <- some result1
t2.a <- some result2

这可能吗?有人可以给我任何有效的解决方案吗?

实现此目的的一种方法是创建一个新的 class,它继承自 A,并具有昂贵的 init_data 作为 class 属性。这是从您的代码派生的简短演示。

class A:
    def __init__(self):
        self.init_data = self._initialize()   # <- same for each thread
        self.a = 0   # <- private for each thread 

    def _initialize(self):
        # Get data from db (high cost)
        print('_initialize called')
        return 1000

    def calculate_a(self, data):
        # Calculate 'a' result from init_data to private 'a' variable
        self.a += self.init_data + data

class MyA(A):
    # Create a single instance of the original class and store its 
    # init_data as a class attribute of MyA
    init_data = A().init_data

    # Get rid of the inherited  _initialize method
    _initialize = None

    # Override the inherited __init__
    def __init__(self):
        self.a = 0

# Test

b = MyA()
b.calculate_a(10)
print(b.a)
c = MyA()
c.calculate_a(100)
print(c.a)
b.calculate_a(20)
print(b.a)

输出

_initialize called
1010
1100
2030

如您所见,A._initialize() 仅在定义 MyA class 时被调用一次。 MyA 的所有实例共享 MyA.init_dataMyA 的任何方法,包括它从 A 继承的方法,将在 [=20] 时使用 MyA.init_data =] 被引用。