The Tesseract's Shadow The Tesseract's Shadow - 1 year ago 158
Python Question

How can I call a Subclass object from a Superclass and is there a better way to do this? (Python 3)

I am creating a game in python(3) and I have a main class with the game loop and a bunch of variables in it. I have a subclass of this to create "path" objects, and I need the variables from the main class. I also need to call the subclass from the main, superclass. Every time I call the subclass, it also calls the main classes init method to pass variables through. The problem is when this happens, it resets the values of all my variables in the main class.

class Main:
def __init__(self):
foo = 0
sub1 = Sub()

def foo_edit(self): += 5

def main(self):
sub2 = Sub()

class Sub(Main):
def __init__(self):
super(Sub, self).__init__() = 0

def foo_edit(self): += 10

I've looked at many other similar questions, but none have given me the answer I need. I tried sub1 in my code(in the init function of main) and this creates a recursion loop error because the init functions call eachother forever. When I call it in the gameloop(or main in this example) it re initializes Main each time it is called, wiping the variables needed in Sub. Before I only had one instance of the "path" so I had no need of class, and had a function. Now that I need multiple "path" objects I am using a subclass of main to get the variables I need.

A solution to this problem that does or does not answer my question(calling a subclass from a superclass might be a bad idea) would be appreciated. Thanks in advance.

EDIT: I could pass the variables needed into the "Sub" class, however I need them to be updated so I would need some sort of update method to make sure the variables passed in are changed in Sub when they are in Main. This is easily doable, but I was wondering if there was easier/better way to do it.

Answer Source

You are misunderstanding the purpose of subclasses. Inheritance isn't for sharing data, it's for making special cases of a general type.

If Sub should be exactly like Main with a few specializations then you should use inheritance. When you say that "Sub" is a subclass of "Main", you are saying "Sub is a Main', not "Sub uses part of Main".

If Sub merely needs access to data in Main, use composition. If Sub needs data from Main, pass an instance of Main to Sub, and have Sub operate on the instance.

For example:

class Main():
    def __init__(self): = 42
        self.sub1 = Sub(self)

class Sub():
    def __init__(self, main):
        self.main = main

    def foo_edit(self): += 10
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download