SuperDisk
SuperDisk

Reputation: 2840

Python: Is passing a main class to other classes a bad idea?

I've got a main class that holds the program's mainloop and other variables and such.

class main:
    def __init__(self):
       blah = 'blah'
       blah2 = 'blah'
       blahhandler = BlahHandler.BlahHandler(self)
       blahhandler2 = BlahHandler.BlahHandler2(self)

    def mainloop(self):
       < IRRELEVANT JUNK >

But is passing 'self' to the blahhandlers a bad idea, so the handlers can do stuff such as..

#In class 'BlahHandler'
self.main.blahhandler2.doBlah()
print(self.main.blah)

Or should I just pass the blahhandler2 directly to the blahhandler rather than passing the whole main class? Sorry if this is incomprehensible just because it all sounds like 'blah'.

Thanks!

Upvotes: 4

Views: 355

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208545

There is nothing wrong with passing your main object to BlahHandler as you are currently doing.

Which one is better depends entirely one what your objects actually represent. Here are a few questions to get you started:

  • Does it make sense for a BlahHandler to have its own reference to a BlahHandler2, or when a BlahHandler is refererring to a BlahHandler2 is it always referring to the BlahHandler2 that it's main owns?
  • Should a BlahHandler really have a reference to a main, or are the attributes to main that should be hidden from BlahHandler?

Ask questions like these about structure early on in development, just because what you currently have works and isn't bad practice, doesn't mean it makes the most sense (but it might!).

Don't worry about passing "the whole main class" from a speed or memory perspective, all you are passing is a reference.

Upvotes: 3

Related Questions