my code has a number of classes, each of them have its own methods to communicate with users, via a console or GUI.
Is it possible to group the methods of the same type into a module, so that, according to user preference, the program may communicate with users via a console or GUI by importing the correct module that contains all the methods (either console or GUI) for the classes?
Well, if I understand your question, lets say you have two modules, first is name consoleUI.py and second is name GUI.py, in your main program, you just do:
Of course both module need to have the same function names, so during your main program you just call lets say UI.giveData(data), and each module handles the data its own way.Code:if user_pref_ui=="c":#"c" for console import consoleUI as UI if user_pref_ui=="g":#g for graphical: import GUI as UI
There is a twist, in my program I have already grouped the connected data and functions into objects. Each object has its own (using the example you gave) "giveData" method. I would like to group all such "giveData" methods across different objects into one module, so that, I could either import all "giveData" in consoleUI version or GUI version depending on user preference. Does Python allow this?
If I don't do this, each class will have to have two versions of "giveData" in the memory, consoleUI and GUI.
hmm... I don't really understand. But I would answer:
and If you want to change the names:Code:from module import Object1,Object2,...
It will only load these specific objects in memory.Code:from module import obj1 as name1,obj2 as name2, obj3 as name3,etc...
Here is one way I can think of:
Is there a better way?
a.py
b.pyCode:def giveDataA(self, x): #method of Class A return x**2 def giveDataB(self, x): #method of Class B return x**3 giveData = [giveDataA, giveDataB]
main.pyCode:def giveDataA(self, x): #method of Class A return x**4 def giveDataB(self, x): #method of Class B return x**5 giveData = [giveDataA, giveDataB]
Code:user_pref_ui = input() if user_pref_ui=="a": #choose A import a as UI if user_pref_ui=="b": #choose B import b as UI class A: def __init__(self): self.var = 5 giveData = UI.giveData[0] class B: def __init__(self): self.var = 10 giveData = UI.giveData[1] Oa = A() Ob = B() print(Oa.giveData(Oa.var)) print(Ob.giveData(Ob.var))
nice thanks....
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks