on the begin I'll say that I was looking for the answer but can't find it and sorry for so basic question.I created program with TTS. I created global variable called "list_merge", but most of you said that global variables are BAD. So I decided to put this list in init. PS. ignore whitespaces, they exist only because I copied it here.
the error is:
AttributeError: 'Ver2ProjectWithTTS' object has no attribute 'list_merge'
import json
import pyttsx
from openpyxl import load_workbook
class Ver2ProjectWithTTS(object):
def __init__(self):
self.read_json_file()
self.read_xml_file()
self.say_something()
self.list_merge = []
def read_json_file(self):
with open("json-example.json", 'r') as df:
json_data = json.load(df)
df.close()
for k in json_data['sentences']:
text_json = k['text']
speed_json = int(k['speed'])
volume_json = float(k['volume'])
dict_json = {'text': text_json, 'speed': speed_json, 'volume': volume_json}
self.list_merge.append(dict_json)
def read_xml_file(self):
tree = et.parse('xml-example.xml')
root = tree.getroot()
for k in range(0, len(root)):
text_xml = root[k][0].text
speed_xml = int(root[k][1].text)
volume_xml = float(root[k][2].text)
dict_xml = {'text': text_xml, 'speed': speed_xml, 'volume': volume_xml}
self.list_merge.append(dict_xml)
def say_something(self):
for item in self.list_merge:
engine = pyttsx.init()
engine.getProperty('rate')
engine.getProperty('volume')
engine.setProperty('rate', item['speed'])
engine.setProperty('volume', item['volume'])
engine.say(cleared_text)
engine.runAndWait()
if __name__ == '__main__':
a = Ver2ProjectWithTTS()
I'm getting
AttributeError: 'Ver2ProjectWithTTS' object has no attribute 'list_merge'
Any ideas how to avoid this error? Well i'm not good in objectivity and I just cant move on without fixing this. PS. with global variable before init def it worked properly.
Thanks for help :)
You have to set if first before you use it:
class Ver2ProjectWithTTS(object):
def __init__(self):
# first set it
self.list_merge = []
self.read_json_file()
self.read_xml_file()
self.say_something()
Anyway don't do any advanced logic in constructors, it's not a good practice. Make a method instead:
class Ver2ProjectWithTTS(object):
def __init__(self):
# first set it
self.list_merge = []
def do_the_job(self):
self.read_json_file()
self.read_xml_file()
self.say_something()
...
instance = Ver2ProjectWithTTS()
instance.do_the_job()
Related
I am just trying to print my raw text from bs4. However, I cant access the attribute from inside one of my methods. But I can access the attribute just fine from outside the class.
import requests
from bs4 import BeautifulSoup
from pprint import pp
import datetime
import time
stocklist = ["wish","clov","baba","pltr",'mu','nio','sofi','tsla','gme','clne',]
class Stock:
def __init__(self,stocklist,s):
self.address = Stock.AG(stocklist,s)
self.soup = Stock.Soup(stocklist,s)
self.volume = Stock.Volume(stocklist,s)
self.price = Stock.Price(stocklist,s)
def AG(stocklist,s):
stockurl = str(('https://robinhood.com/stocks/'+stocklist[s]))
return(stockurl)
def Soup(stocklist,s):
r = requests.get('https://robinhood.com/stocks/'+stocklist[s])
soup = str(BeautifulSoup(r.content, 'lxml'))
return(soup)
def Volume(stocklist,s):
print(stocklist[s].soup) # does not work
def Price(stocklist,s):
pass
for s in range(len(stocklist)):
stocklist[s] = Stock(stocklist,s)
print(stocklist[s].address)
print(stocklist[s].volume)
print(stocklist[s].soup) #works
So this is because when you are calling the volume function stocklist[s] still refers to the string not to the object. Think about when you are calling the init method and hows it being called before the list is overwritten.
The very quick and dirty solution I came up with which should not be deployed but highlights the problem is to change you init method to this.
def __init__(self,stocklist,s):
self.address = Stock.AG(stocklist,s)
self.soup = Stock.Soup(stocklist,s)
stocklist[s] = self
self.volume = Stock.Volume(stocklist,s)
self.price = Stock.Price(stocklist,s)
Can anyone explain why this keeps happening to me?
class TourAgency:
def __init__(self):
self._tours = {}
self._scheduledtours = {}
self._customers = {}
self._booking = {}
def addTour(self,code,tour):
self._tours[code] = tour
def addscheduledtours(self,code,scheduledtour):
self._scheduledtours[code] = scheduledtour
def addCustomer(self,code,customer):
self._customers[code] = customer
def addBooking(self,bookingId,booking):
self._booking[bookingId] = booking
def searchscheduledtours(self,code):
if code in self.scheduledtours.keys():
return self._scheduledtours[code]
else:
return None
mytour = TourAgency()
t1 = Tour("KO111","Discover Korea",8,7,1449.36)
print(t1)
ta = mytour.addTour('KO111',t1)
print(TourAgency.tours)
I get an error saying:
print(TourAgency.tours)
AttributeError: type object 'TourAgency' has no attribute 'tours'
Your class hasn't got the tours attribute, it has only got the _tours attribute. Maybe you want to use it instead.
Remember that, in Python, if an attribute name starts with an underscore, it means that the attribute should be private and not intended to be used by the user.
I hope this could help you! Cheers!
guys i have a problem with my variable.
When i instance my class my variable dossierProd and dossierModif is not empty but when i want use another function she is empty.
import glob
class OBDI:
dossierProd = ""
dossierModif = ""
listeFichierProd = []
listeFichierModif = []
def __init__(self, dossierP, dossierM):
dossierProd = dossierM
dossierModif = dossierM
def recupListeFichier(self):
HERE MY VARIaBLE dossierProd & dossierModif as empty
for fichier in glob.glob(str(self.dossierProd) + '*.csv'):
self.listeFichierProd.append(fichier.replace("\\", "/"))
for fichier in glob.glob(str(self.dossierModif) + '*.csv'):
self.listeFichierModif.append(fichier.replace("\\", "/"))
if len(self.listeFichierProd) != len(self.listeFichierModif):
print "toto
Have you got an idea why my variable is empty ?
Thx to your response.
Sorry for my bad english ;)
Oh thanks, this error is so stupid.
I'm to be accustomed to java
You haven't initialized dossierP and dossierM instance variables in __init__():
def __init__(self, dossierP, dossierM):
self.dossierProd = dossierM
self.dossierModif = dossierM
Watch self. here.
Also, since it appears that dossierProd and dossierModif variables make sense only for when you have an instance of a OBDI class, remove dossierProd = "" and dossierModif = "" lines.
Also, you probably don't want to share listeFichierProd and listeFichierModif lists between OBDI class instances - initialize lists in __init__():
def __init__(self, dossierP, dossierM):
self.dossierProd = dossierM
self.dossierModif = dossierM
self.listeFichierProd = []
self.listeFichierModif = []
and remove listeFichierProd = [] and listeFichierModif = [] lines.
Make sure you understand what is discussed in the following threads:
Instance variables vs. class variables in Python
python class instance variables and class variables
Hope that helps.
I am a total python beginner and I have a variable created in a class of a file commandline_reader.py that I want to access from another script. I tried to do it by making the variable global, which doesn't work.
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
global output
output = []
def run(self):
# do stuff
a = 'somevariable'
output.append(a)
When I run myscript.py I always get a NameError: name 'output' is not defined. I've read that this is because global variables are only defined within a module. How do I correctly access the output variable in my script?
ouch. The whole reason object oriented programming takes place is to avoid the use of global variables. Make them instance variables to access them anywhere in the class.
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) #output is now part of the instance Commandline reader and can be accessed anywhere inside the class.
clr = Commandline_Reader(argstring='--get_serial_number')
clr.run()
print clr.output
>>>['somevariable']
Make output an instance attribute:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = [] # note use of self here
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) # and here
The access it via the instance:
print reader.output
Maybe class attribute is more appropriate for you?
class Commandline_Reader:
output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)
Just return the Value from the run() Method
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
output = reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)
return self.output
I realize there are other threads addressing this problem but as I am fairly new to 'Classes' and have already constructed my class structure ... I would like to find a method that I can integrate into my code. I'm sure this will NOT be a difficult one to answer!
First File: NameResult.py
from NameAssign import *
NameList = NameWorks()
print(NameList.InputNames(NameVar))
Second File: NameAssign.py
class NameWorks:
def __init__(self, NameVar = []):
self.NameVar = NameVar
def InputNames(self, NameVar):
global NameVar
NameVar = ['harry', 'betty', 'sam']
Result:
NameError: name 'NameVar' is not defined
All replies are much appreciated ...
NameVar is not defined in NameAssign; it only exists within NameAssign.NameWorks.InputNames() as a local variable. The easiest way to fix this is to define it in NameAssign at the global level.
Edit:
It turns out that this is what you want to do:
NameResult.py
import NameAssign
namelist = NameAssign.NameWorks(['harry', 'betty', 'sam'])
print namelist.InputNames() # or print(...) for Py3k
NameAssign.py
class NameWorks(object):
def __init__(self, names):
self.names = names
def InputNames(self):
return self.names