Class 同实例下的继承

Class inheritance under same instance

我正在尝试让多个 class 从一个 class 继承,但使用相同的实例,而不是每次都创建不同的实例。

class ClassA(object):
    def __init__(self):
        self.process_state = "Running"
        self.socket_list = []
    def method_a(self):
        print("This is method a")
        

class ClassB(ClassA):
    def __init__(self):
        super().__init__()
        
    def method_b(self):
        if self.process_state == "Running":
            self.socket_list.append("From Method B")
            print(self.socket_list)
            print("This is method b")


class ClassC(ClassA):
    def __init__(self):
        super().__init__()
        
    def method_c(self):
        if self.process_state == "Running":
            print(self.socket_list)
            self.socket_list.append("From Method C")
            print("This is method c")   
            print(self.socket_list)

   

函数运行:

CB = ClassB() 
CB.method_b() 
CB.method_b()

CC = ClassC() 
CC.method_c()

结果:

['From Method B']
This is method b
['From Method B', 'From Method B']
This is method b
[]
This is method c
['From Method C']

想要的结果:

['From Method B']
This is method b
['From Method B', 'From Method B']
This is method b
['From Method B', 'From Method B']
This is method c
['From Method B', 'From Method B', 'From Method C']

我正在尝试让多个 class 从一个 class 继承,但使用相同的实例而不是每次都创建不同的实例。

实现此目的的一种方法是将套接字列表设为静态变量,但我不确定是否推荐这样做。

class ClassA(object):
    socket_list = []
    def __init__(self):
        self.process_state = "Running"
    def method_a(self):
        print("This is method a")

输出:

['From Method B']
This is method b
['From Method B', 'From Method B']
This is method b
['From Method B', 'From Method B']
This is method c
['From Method B', 'From Method B', 'From Method C']