0

I have created an application which has only 1 big class that wrap all of functions. The code run smoothly as it should be.

The code can be divided into sections such as: GUI, pure block codes to handle tasks.

I want to seperate the original class into 2 classes, 1 will be the GUI for application and the other is block code that handles tasks.

The problem is that when I do that, 2 classes use the other's instance variables. How can I fix this, please help, thank you.

Example of the original class:

Class App:
    def __init__(self):
        self.var1 = 'first variable'
        self.var3 = 'third variable'
    def method1(self):
        self.var2 = 'second variable'
        print(self.var3) 
    def method2(self):
        print(self.var2)  
        self.method1()

Here is the example of the 2 new classes (I just split them up and haven't modify anything):

Class GUI:
    def __init__(self):
        self.var1 = 'first variable'
    
    def method1(self):
        self.var2 = 'second variable'
        print(self.var3)  # <-- var3 is belonged to class Core

Class Core:
    def __init__(self):
        self.var3 = 'third variable'
    def method2(self):
        print(self.var2)  # <-- var 2 is belonged to class GUI
        self.method1()  # <-- method1 belonged to class GUI too
ntk
  • 33
  • 1
  • 4
  • how about You keep all the variables in the __init__ method? which should have been the case anyways. so when You split some variables are just not being used – Matiiss Apr 02 '21 at 02:29
  • Putting instance variables in ```__init__``` is just about declaring it, right? 'cause I have to use them later in class's methods though – ntk Apr 02 '21 at 03:48
  • sort of like that (it is not mandatory since You can define them in other functions but it just throws a PEP error or sth (the code still runs)) but in this case it will just help You, but actually the answer here is also a great way of going about it – Matiiss Apr 02 '21 at 10:41

1 Answers1

1

I think this is the solution:

class GUI:
    var2 = None

    def __init__(self):
        self.var1 = 'first variable'

    @staticmethod
    def method1():
        GUI.var2 = 'second variable'
        print(Core.var3)  # <-- var3 is belonged to class Core


class Core:
    var3 = None
    
    def __init__(self):
        Core.var3 = 'third variable'

    @staticmethod
    def method2():
        print(GUI.var2)  # <-- var 2 is belonged to class GUI
        GUI.method1()  # <-- method1 belonged to class GUI too

You should make your variables and methods static. You can read more about static methods and variables in python here: Are static class variables possible in Python?

crackanddie
  • 688
  • 1
  • 6
  • 20