How to pass a filename as a Class variable? - python

I am trying to build a Tkinter app which allows you load documents and then analyse them. I must admit I am still getting to grips with object-oriented programming, so apologies if this is a simple answer.
I have built this Class to hold the filepath variables for the rest of the app to use.
class Inputs:
def __init__(self, CV, JS):
self.CV = CV
self.JS = JS
def cv(self, input):
self.CV = input
def js(self, input):
self.JS = input
However everytime I try to pass the following:
b = ‘CV_test.txt’
Inputs.cv(b)
I get the following error.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3319, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-f21fa013f9ae>", line 1, in <module>
Inputs.cv(b)
TypeError: cv() missing 1 required positional argument: 'input'
Is it not possible to pass a filepath as a Class variable?
Supplementary question: Will this approach enable me to call on these variables in other classes at a later date?

Class variables are defined outside of __init__:
class Inputs:
CV = None
JS = None
SELF_JS = None
def cv(self, inp):
Inputs.CV = inp
def js(self, inp):
Inputs.JS = inp
def self_js(self, inp):
# this dont work...
self.SELF_JS = inp
Inputs.CV = 'CV_Test.txt'
my_inputs1 = Inputs()
my_inputs1.js('JS_Test.txt')
my_inputs1.self_js('SELF_Test.txt')
my_inputs2 = Inputs()
print(my_inputs2.JS)
print(my_inputs2.CV)
print(my_inputs2.SELF_JS) # Not available in my_inputs2 !!
Out:
JS_Test.txt
CV_Test.txt
None

Related

Python OOP error calling function within function

I just started learning OOP and was trying to create a class
but apperently i am not able to call the fuction within function
class WordPic:
def __init__(self,filename,outputname):
self.skipped = ["was","in","the","have","think","these","we","as"]
self.filename = filename
self.outputname = outputname
self.txt_freq = {}
def get_frequancy(self):
with open (self.file_location,"r") as f:
lines = f.read().lower()
splited_lines = lines.split()
for line in splited_lines:
if line not in self.skipped and line.isalpha():
line = line[0].upper() + line[1:]
if line not in self.txt_freq:
self.txt_freq[line] = 1
else:
self.txt_freq[line] += 1
return self.txt_freq
def create_pic(self):
cloud = wordcloud.WordCloud(background_color="white")
cloud.generate_from_frequencies(self.txt_freq)
cloud.to_file("{}.jpg".format(self.outputname))
def create(self):
get_frequancy(self)
create_pic(self)
print("created")
wc = WordPic("try.txt","done")
wc.create()
the error that i encounter is
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [190], in <cell line: 2>()
1 wc= WordPic("try.txt","done")
----> 2 wc.create()
Input In [188], in WordPic.create(self)
28 def create(self):
---> 29 get_frequancy(self)
30 create_pic(self)
31 print("created")
NameError: name 'get_frequancy' is not defined
i am not able to find my way around if anyone can help. thank you
get_frequancy is not a nonlocal variable; it's a class attribute. It has to be accessed as such. (The same goes for create_pic.)
def create(self):
self.get_frequancy()
self.create_pic()
print("created")
(While WordPic.get_frequancy(self) would be sufficient in the example shown, calling instance methods like this runs into problems once you start taking inheritance into account.)

Attribute Error in python. Object has no attribute

This code is part of a bigger program that uses the google Sheets API to get data from a cloud database (not really relevant, but a bit of context never hurt!)
I have this black of code in one python file named 'oop.py'
class SetupClassroom:
def __init__(self, arraynumber='undefined', tkroot='undefined'):
self.arraynumber = arraynumber
self.tkroot = tkroot
def setarraynumber(self, number):
from GUI_Stage_3 import showclassroom
self.arraynumber = number
print ('set array number:', number)
showclassroom()
def settkroot(self, tkrootinput):
self.tkroot = tkrootinput
self.tkroot has been assigned by another part of the code. This bit works, as I have already tested that it is being assigned, however, when I call 'self.tkroot' in another another file like this
def showclassroom():
from oop import SetupClassroom
username = current_user.username
classnumber = getnumberofuserclassrooms(username)
if SetupClassroom.arraynumber > classnumber:
errorwindow('you are not enrolled in that many classrooms!')
else:
classtoget = SetupClassroom.arraynumber
print('classtoget:', classtoget)
root = SetupClassroom.tkroot
name_label = Label(root, text=classtoget)
getclassroom(username, classtoget)
SetupClassroom = SetupClassroom
I get this error
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage2_better.py", line 176, in <lambda>
l0 = ttk.Button(teacher_root, text=button0text, command=lambda: (SetupClassroom.setarraynumber(SetupClassroom, number=button0text), SetupClassroom.settkroot(SetupClassroom, 'teacher_root')))
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/oop.py", line 99, in setarraynumber
showclassroom()
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage_3.py", line 29, in showclassroom
root = SetupClassroom.tkroot
AttributeError: type object 'SetupClassroom' has no attribute 'tkroot'
I tried setting it up in the python console and it worked, so I have no idea what the problem is.
If anyone could help, it would be very much appreciated
Thanks!
John
You should create an instance of class, it will create the attribute in __init__, self.tkroot is the attribute of instance not class:
setupClassroom = SetupClassroom()
print(setupClassroom.tkroot)
Hope that will help you.

Python - Creating an instance of a module, getting an error

I am creating a universal text field that can be used in many python turtle projects. I am trying to create an instance of it but I get this error:
>>> import TextField
>>> tf = TextField('None', False)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tf = TextField('None', False)
TypeError: 'module' object is not callable
>>>
What in a module causes this type of error? I completely wrote this module and I'm getting an error creating an instance of it :( ... What do I need in this module to make it 'callable'? I have tried adding a def __call__(self): but that doesn't affect the problem at all, nor create any errors.
Here is the beginning of the script where the problem is most likely happening:
# Created by SUPERMECHM500 # repl.it
# Edited by cdlane # stackoverflow.com
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {
'1':'!',
'2':'#',
'3':'#',
'4':'$',
'5':'%',
'6':'^',
'7':'&',
'8':'*',
'9':'(',
'0':')'
}
def __init__(self, command, CanBeEmpty): # Ex. textField = TextField('Execute()', True)
self.CmdOnEnter = command
self.turtle = Turtle()
self.CanBeEmpty = CanBeEmpty
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
......
The module is not the class. If your class TextField is in a module called TextField, then it is referred to as TextField.TextField.
Or change your import to
from TextField import TextField

instantiate object inside of class

Im trying to understand why I cannot access the methods on an object that is instantiated inside of a class. For example i'm attempting to build a script that utilizes the python-pptx library and I want to wrap the entire slide creation within a class to abstract it and make it a bit more reusable based on my configuration.
class Builder():
def __init__(self, template='template.pptx', output_file='out.pptx'):
self.cust_name = ''
self.author = ''
self.job_title = ''
self.present_date = ''
self.assessment_type = ''
self.template = template
self.agenda = ['Overview','Resources']
self.outfile = output_file
self.prs = Presentation('template.pptx') <--- This is what im referring to.
def addAgendaSlide(self):
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA]) <-- When trying to access this
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[10].text = 'A test Agenda slide'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
for para in self.agenda:
p = agenda_slide.placeholders[15].text_frame.add_paragraph()
p.text = para
Traceback (most recent call last):
File "test.py", line 19, in <module>
test.addAgendaSlide()
File "/dev/pythonpptx/DocMaker/Slides.py", line 89, in addAgendaSlide
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])
AttributeError: 'Presentation' object has no attribute 'add_slide'
If I use the same bits of code outside the class it works fine. I do have other methods in the class that are fine, it seems to be my implementation of the Presentation() bit that is messing me up.
The following works fine:
prs = Presentation('template.pptx')
agenda_slide = prs.slides.add_slide(prs.slide_layouts[AGENDA])
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
prs.save('out.pptx')
I think your problem is you are forgetting to add slides as follows:
agenda_slide = self.prs.slides.add_slide(self.prs.slide_layouts[AGENDA])
instead of
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])

zipline run_pipeline and positional arguments

I'm using Zipline-1.1.1, Python3.4.6 to create a dynamic stock selector as follows:
from zipline.pipeline import Pipeline, engine
from zipline.pipeline.factors import AverageDollarVolume, Returns
def make_pipeline():
dollar_volume = AverageDollarVolume(window_length=1)
high_dollar_volume = dollar_volume.percentile_between(N, 100)
recent_returns = Returns(window_length=N, mask=high_dollar_volume)
low_returns = recent_returns.percentile_between(0, n)
high_returns = recent_returns.percentile_between(N, 100)
pipe_columns = {
'low_returns': low_returns,
'high_returns': high_returns,
'recent_returns': recent_returns,
'dollar_volume': dollar_volume
}
pipe_screen = (low_returns | high_returns)
pipe = Pipeline(columns=pipe_columns, screen=pipe_screen)
return pipe
I initialize a pipeline object with:
my_pipe = make_pipeline()
But when I try to populate the Pipeline, it fails with:
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Traceback (most recent call last):
File "<input>", line 1, in <module>
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
TypeError: run_pipeline() missing 1 required positional argument: 'end_date'
I can't figure out what is wrong, any help is much appreciated.
If I understand correctly, you're using this library.
As far as I can see from that code, to be able to use run_pipeline method you have to instantiate on of pipeline engines before, e.g. SimplePipelineEngine. You need that because PipelineEngine is a class, even abstract class, not an object.
So you have to create an object of SimplePipelineEngine class and then call run_pipeline on it. You can do it this way:
your_engine = SimplePipelineEngine(get_loader=your_loader, calendar=your_calendar, asset_finder=your_asset_finder)
your_eninge.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Of course you have to create your_loader etc. first.
Here is example of SimplePipelineEngine usage. I hope it will help.

Categories

Resources