Home > Software design >  Class inheritance under same instance
Class inheritance under same instance

Time:01-21

I am trying to have multiple classes inherit from one class but use the same instance and not create a different instance each time.

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)

   

Functions ran:

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

CC = ClassC() 
CC.method_c()

Result:

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

Desired result:

['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']

I am trying to have multiple class inherit from one class but use the same instance and not create a different instance each time.

CodePudding user response:

One way you can achieve this is by making the socket list a static variable, though I'm not sure if this is recommended.

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

Output:

['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']
  •  Tags:  
  • Related