Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Class Inheritance under same instance

I am trying to have multiple class 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading