The problem I am having now is the user inputs are being called twice. Is there any better way to share self between python scripts more easily and avoid calling input twice. I read about multiprocessing module in python, but couldn't use it.
This is a short example:
script1.py:
class importparam(object):
def dataset1(self):
self.var1=1
self.var2=2
self.var3=3
self.var4=input('enter var4 : ')
def dataset2(self):
self.const1=11
self.const2=22
self.const3=33
self.const4 = input('enter const4 : ')
script2.py:
from main import main_
class reader_(main_):
def __init__(self):
super(reader_, self).__init__()
def addition(self):
self.add1 = self.const1+self.const2
self.add2 = self.const3+self.const4
def multiply(self):
self.mult1 = self.var1+self.var2
self.mult2 = self.var3+self.var4
main.py
from script1 import importparam
class main_(importparam):
def __init__(self):
super(main_, self).dataset1()
super(main_, self).dataset2()
def fun1(self):
from script2 import reader_
r=reader_()
val=1
if val==1:
r.addition()
else:
r.multiply()
if __name__=='__main__':
main_().fun1()
Related
Given this example code where we have a series of log processors, I can't help feeling there ought to be a more pythonic/efficient way of deciding which log processor to use to process some data:
class Component1ErrorLogProcessor:
def process(logToProcess):
# Do something with the logs
pass
class Component2ErrorLogProcessor:
def process(logToProcess):
# Do something with the logs
pass
class LogProcessor:
def __init__(self):
self.component1 = Component1ErrorLogProcessor()
self.component2 = Component2ErrorLogProcessor()
def process_line(self, line, component):
if component == "Component1Log-" or component == "[Component1]":
self.component1.process_errors(line)
elif component == "Component2Log-" or component == "[Component2]":
self.component2.process_errors(line)
I'd personally use the idea of registry, so you map each class to component names.
There are a bunch of different ways to go about this, here's a quick example by using a base class:
class ComponentLogProcessor(object):
_Mapping = {}
#classmethod
def register(cls, *component_names):
for name in component_names:
cls._Mapping[name] = cls
#classmethod
def cls_from_component(cls, component):
return cls._Mapping[component]
class Component1ErrorLogProcessor(ComponentLogProcessor):
def process(logToProcess):
# Do something with the logs
pass
Component1ErrorLogProcessor.register('Component1Log-', '[Component1]')
class Component2ErrorLogProcessor(ComponentLogProcessor):
def process(logToProcess):
# Do something with the logs
pass
Component2ErrorLogProcessor.register('Component2Log-', '[Component2]')
class LogProcessor:
def process_line(self, line, component):
ComponentLogProcessor.cls_from_component(component).process_errors(line)
I am trying to re-execute a file's code within the program
main.py
# Within the main.py
exec(open('PDM/Path2.py').read())
PDM/Path2.py
# Within the file being read
import tkinter as tkin
class path2_wind:
def __init__(self):
self.path2 = tkin.Tk()
self.path2.geometry('400x430')
self.path2.title('PDM/Path_2')
self.sight = tkin.PhotoImage(file='PDM/Path_2.Sight.png')
self.back = tkin.Label(self.path2,image=self.sight)
self.back.pack(side='top')
self.frame = tkin.Frame(self.path2)
self.hello = tkin.Label(self.frame,text='Welcome User (Name Here)')
self.back = tkin.Button(self.frame,text='Back',command = self.path2.destroy)
self.frame.pack(side='top')
self.hello.pack(side='left')
self.back.pack(side='left')
tkin.mainloop()
open = path2_wind()
The error displayed is TypeError: 'path2_wind' object is not callable.
It is because you have override the standard function open() by the line:
open = path2_wind()
So when the following code is being executed again:
exec(open('PDM/Path2.py').read())
it raises the exception since open is not the standard function now.
Use other name instead of open, for example:
win = path2_wind()
As #TheLizzard stated in the comment, it is better to use import instead of exec():
main.py
from PDM.Path2 import path2_wind
win = path2_wind()
...
PDM/Path2.py
import tkinter as tkin
class path2_wind:
def __init__(self):
self.path2 = tkin.Tk()
self.path2.geometry('400x430')
self.path2.title('PDM/Path_2')
#self.sight = tkin.PhotoImage(file='PDM/Path_2.Sight.png')
self.sight = tkin.PhotoImage(file='images/nier-a2.png')
self.back = tkin.Label(self.path2,image=self.sight)
self.back.pack(side='top')
self.frame = tkin.Frame(self.path2)
self.hello = tkin.Label(self.frame,text='Welcome User (Name Here)')
self.back = tkin.Button(self.frame,text='Back',command = self.path2.destroy)
self.frame.pack(side='top')
self.hello.pack(side='left')
self.back.pack(side='left')
tkin.mainloop()
if __name__ == '__main__':
win = path2_wind()
I need some help regarding modules & class and how to share data and methods.
I have been working on a Python program for a while and it has gotten too big to deal with in its original form which did not use classes. The program is about 6000 lines long and uses Tkinter with multiple screens. I figured the logical breakdown into classes would follow the user interface with each screen being its own class. Then I would have another class that stores all the "global" data.
So far, with everything still in one file, and it is working. However, I am now trying to break these classes out into separate modules by saving them in their own files. This is where things got really bad for me. I have read many tutorials and texts on classes and have seen a number of posts about my same problem here on Stack Overflow, but I still can't figure out what to do.
As my actual program is so big, I created a very simple program that shows what I need to do...
#main.py
class data:
def __init__(self):
self.A = "A"
self.B = "B"
self.C = "C"
self.All = ""
class module_1:
def __init__(self):
place_holder = "something"
def add_1_2(self):
d.All = d.A + d.B
print("new_string=", d.All)
class module_2:
def __init__(self):
place_holder = "something"
def combine_it_all(self):
m1.add_1_2()
d.All = d.All + d.C
d = data()
m1 = module_1()
m2 = module_2()
m2.combine_it_all()
print("d.All = ", d.All)
print("END OF PROGRAM")
The program above shows how I want to access data in other classes and use their methods. However, I also need to break out the program into modules so that they are much smaller and easier to work with. So, I tried to break out each class and put it in its own file (module) and now I don't know how to access data or methods in other classes which come from modules. Here are the breakdowns of each file...
#data_p.py
class data:
def __init__(self):
self.A = "A"
self.B = "B"
self.C = "C"
self.All = ""
#module_1_p.py
class module_1:
def __init__(self):
place_holder = "something"
def add_1_2(self):
d.All = d.A + d.B
print("new_string=", d.All)
#module_2_p.py
class module_2:
def __init__(self):
place_holder = "something"
def combine_it_all(self):
m1.add_1_2()
d.All = d.All + d.C
#main.py
from data_p import data
from module_1_p import module_1
from module_2_p import module_2
d = data()
m1 = module_1()
m2 = module_2()
m2.combine_it_all()
print("d.All = ", d.All)
print("END OF PROGRAM")
As you can see, there a problems with attributes and methods being addressed, but not yet instantiated. Unfortunately, I am getting up there in years, and certainly not the brightest programmer around, but I am hoping someone can show me how to make this simple example work so that I can fix my actual program.
The issue is classes are instantiated, but each instance has no idea about the other, one way to fix it is to pass references in the method calls.
It's probably possible to do better in the actual context, but with these changes, your example will work:
#module_1_p.py (line 5 changed)
class module_1:
def __init__(self):
place_holder = "something"
def add_1_2(self, d):
d.All = d.A + d.B
print("new_string=", d.All)
#module_2_p.py (lines 5 and 6 changed)
class module_2:
def __init__(self):
place_holder = "something"
def combine_it_all(self, m1, d):
m1.add_1_2(d)
d.All = d.All + d.C
#main.py (line 9 changed)
from data_p import data
from module_1_p import module_1
from module_2_p import module_2
d = data()
m1 = module_1()
m2 = module_2()
m2.combine_it_all(m1, d)
print("d.All = ", d.All)
print("END OF PROGRAM")
I am building a calculator app, and I solved a lot of problems except this one. It is bigger than me to solve it, I tried nearly everything except 1 way that I am thinking of it right now is: making the program in one (.py) file.
My program is designed in Kivy and I made the app in two python files, so here is the problem: the main screen has several choices to open a new page, and that page must have a button that make the app gets back to the main screen, and this button did not work.
A variable has just disappeared magically .. called 'winroot'!
Here is the code (main.py):
class Base(App):
def build(self):
global winroot
winroot = TheMainScreen()
mnsc = MainScreen()
winroot.add_widget(mnsc)
return winroot
class TheMainScreen(FloatLayout):
def back(self, obj=1):
print('pressed')
winroot.clear_widgets()
winroot.add_widget(MainScreen())
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
self.B1 = Button(text='Base Calculator\n\n\n', on_press=self.basecalc)
def basecalc(self, obj):
winroot.clear_widgets()
from calculator.basecalculator import BaseCalculator
winroot.add_widget(BaseCalculator())
and this is for the second python file (basecalculator.py):
class BaseCalculator(FloatLayout):
def __init__(self, **kwargs):
super(BaseCalculator, self).__init__(**kwargs)
self.B11 = Button(size_hint=(.08, .13), on_release=self.prev)
def prev(self, obj=1):
from calculator.main import TheMainScreen
a = TheMainScreen()
a.back()
and here is the Error that is showing up :
File "C:\Users\work\PycharmProjects\Kivy\calculator\basecalculator.py", line 95, in prev
a.back()
File "C:\Users\work\PycharmProjects\Kivy\calculator\main.py", line 26, in back winroot.clear_widgets()
NameError: name 'winroot' is not defined
since winroot is a global variable created inside a function, you have to declare it as global in every function you use it.
Or, you know, instead of global, set is as instance attribute and pass it around, then you don't need globals:
class Base(App):
def build(self):
self.winroot = TheMainScreen()
self.mnsc = MainScreen(self.winroot)
self.winroot.add_widget(self.mnsc)
return winroot
class TheMainScreen(FloatLayout):
def back(self, obj=1):
print('pressed')
self.clear_widgets()
self.add_widget(MainScreen())
class MainScreen(FloatLayout):
def __init__(self, winroot, **kwargs):
self.B1 = Button(text='Base Calculator\n\n\n', on_press=self.basecalc)
self.winroot = winroot
def basecalc(self, obj):
self.winroot.clear_widgets()
from calculator.basecalculator import BaseCalculator
self.winroot.add_widget(BaseCalculator())
I'm trying to write some xml by this piece of code
docs = XmlReportGenerator()
docs.AddMatchRow('FC Barcelona','Madryt','5:0')
docs.Save()
and I wrote my own method:
from lxml import etree
class XmlReportGenerator:
""""""
root = etree.Element('results')
doc = etree.ElementTree(root)
#----------------------------------------------------------------------
def __init__(self):
""""""
def AddMatchRow(self,teamA,teamB, score):
pageElement = etree.SubElement(root,'Flight',teamA, teamB, score)
""""""
def Save(self,path = None):
outFile = open('Matches.xml', 'w')
doc.write(outFile)
NameError: global name 'root' is not defined
Process terminated with an exit code of 1
done
NameError: global name 'doc' is not defined
Process terminated with an exit code of 1
done
Am I missing something? I'm a newbie in python (I have more experience in c#).
Python is explicit. Instance variables must be prepended with self.. Class variables must be prepended with then name of the class.
Here's a fixed version. The original SubElement call was incorrect as well:
from lxml import etree
# derive from 'object' if Python 2.X (it is default in Python 3.X)
class XmlReportGenerator(object):
def __init__(self):
# clearer to init instance variables here.
self.root = etree.Element('results')
self.doc = etree.ElementTree(self.root)
def AddMatchRow(self,teamA,teamB, score):
# Need self.root here
pageElement = etree.SubElement(self.root,'Flight')
# Added data elements (or did you want attributes?)
etree.SubElement(pageElement,'teamA').text = teamA
etree.SubElement(pageElement,'teamB').text = teamB
etree.SubElement(pageElement,'score').text = score
def Save(self,path = None):
outFile = open('Matches.xml', 'w')
# Need self.doc here
self.doc.write(outFile)
# This code will run if the script is executed directly,
# but will be skipped if the script is imported by another script.
if __name__ == '__main__':
docs = XmlReportGenerator()
docs.AddMatchRow('FC Barcelona','Madryt','5:0')
docs.Save()
self is there for a reason. Use self.root, not root