Search code examples
pythonclassloose-coupling

Keeping classes loosely coupled and sharing data


I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.

Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?

As an example

class Window():
    def __init__(self, parent=None):
        self.parent = parent
    def doStuff(self):
        #do work here

class ParseMyWork(Window):
    def __init__(self, parent=None):
        self.parent=parent

I often find myself doing stuff like the above giving objects to class Window or simply inheriting everything from them as in ParseMyWork

There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.

Any answers to the question don't necessarily have to be in python, but it will be helpful if they are


Solution

  • If I'm understanding your question correctly, I would say that inheritance is not necessary in your case. Why not give ParseMyWork a function for dealing with a specific Window task?

    class Window():
      def __init__(self, parent=None):
        self.parent = parent
    
      def doStuff(self):
        #do work here
    
    class ParseMyWork():
      def __init__(self, parent=None):
        self.parent=parent`
    
      def doWindowActivity(self, window):
        window.doStuff
    

    Then you can use the function like this

        work_parser = ParseMyWork()
        window = Window()
        work_parser.doWindowActivity(window);
    

    That way you can use your work_parse instance with any window instance.

    Apologies in advance for my Python, it's been a while so if you see any rookie mistakes, do point them out.