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!
Related
I am trying to add new objects to a class(emne) but the new instances of the class needs to be created using user input. So i need a way to be able to chose the name for the object and set some of the values of the objects with user input.
I have already tried to create a function that passes the value of the user input into a x = emner(x) to create it but it only returns:
AttributeError: 'str' object has no attribute 'fagKode'
so i think my issue is that the value of the input is created as a string so that it is not understood as a way to create the function
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne():
nyttEmne = input("test:")
nyttEmne=Emne(nyttEmne)
expected result is that the code creates a new instance of the class.
If by choosing a name you mean your fagKode attribute, what you need is:
fagKode = input('Enter code: ')
Emne(fagKode)
You're adding the instances of Enme to the list in the constructor, so you don't need to save them to a variable.
Alternatively, you can handle that in the function:
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
def leggTilEmne():
nyttEmne = input("test:")
enme.append(Emne(nyttEmne))
I'm not sure what exactly you are asking, since you haven't responded to the comments. So,
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne(self, value): # <--- is this what you want
self.nyttEmne= Emne(value)
This is an example of when to use a class method. __init__ should not be appending to a global variable, though. Either 1) have the class method append to a class attribute, or 2) have it return the object and let the caller maintain a global list.
emne = []
class Emne:
emne = []
def __init__(self, fag_kode):
self.fag_kode = fag_kode
self.karakter = ""
#classmethod
def legg_til_emne_1(cls):
nytt_emne = input("test:")
cls.emne.append(cls(nytt_emne))
#classmethod
def legg_til_emne_2(cls):
nyttEmne = input("test:")
return cls(nyttEmne)
Emne.legg_til_emne_1() # Add to Emne.emne
e = Emne.legg_til_emne_2()
emne.append(e)
I'm using property method in class to get a subset of user's input:
class deck:
def __init__(self, card_list):
self.cards = card_list
self.cards_slice = []
def get_deal_card(self):
return self.cards_slice
def set_deal_card(self, count):
if count > len(self.cards):
raise Exception("Process failed. Out of index.")
else:
self.cards_slice = self.cards.pop(count)
deal_card = property(get_deal_card, set_deal_card)
d1 = deck([['A',1],['B',1]])
d1.deal_card(0)
It returns type error "List object is not callable". I know this error occurs when I previously defined a list with a name that I used somewhere else. However I still can't see what I do wrong in this program.
Thanks!
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()
I am learning Python out of a book and have written myself a long quiz/type game which prints a summary at the end. However, the summary looks for attributes that will not always exist depending on what choices have been made by the user.
I have abstracted this into a basic example to show what I am trying to do. Essentially, I just want to run an attribute error check, for every variable that does not have an attribute, create an attribute with a default value of N/A.
In the below example, I would want it to print:
Forename: Joe
Surname: Bloggs
Smith Test: N/A
Test 4: N/A
I created a class called CodeCleaner which I was going to use to set the N/A values, but got very stuck!
class QuestionSet(object):
next_set = 'first_set'
class ClaimEngine(QuestionSet):
def current_set(self):
last_set = "blank"
while_count = int(0)
quizset = Sets.subsets
ParentSet = QuestionSet()
while ParentSet.next_set != last_set and int(while_count)<50:
quizset[ParentSet.next_set].questioning()
while_count = while_count+1
class FirstSet(QuestionSet):
def questioning(self):
self.value1 = raw_input("Forename:\n")
QuestionSet.next_set = "second_set"
class SecondSet(QuestionSet):
def questioning(self):
self.value2 = raw_input("Surname:\n")
if self.value2 == "Smith":
self.value3 = "He's a Smith!"
self.value4 = "Test val 4"
QuestionSet.next_set = "summary"
else:
QuestionSet.next_set = "summary"
class CodeCleaner(QuestionSet):
def questioning(self):
mapping = Sets()
sets = mapping.subsets
variable_list = {
[sets['first_set']].value1,
[sets['second_set']].value2,
[sets['second_set']].value3,
[sets['second_set']].value4
}
#while key_no < 4:
# try:
# print variable_list
# except AttributeError:
class Summary(QuestionSet):
def questioning(self):
mapping = Sets()
sets = mapping.subsets
print "Forename:",sets['first_set'].value1
print "Surname:",sets['second_set'].value2
print "Smith Test:",sets['second_set'].value3
print "Test 4:",sets['second_set'].value4
exit(0)
class Sets(object):
subsets = {
'first_set': FirstSet(),
'second_set': SecondSet(),
'summary': Summary()
}
run = ClaimEngine()
run.current_set()
I feel quite lazy asking this question, however, I've been wrestling with this for a few days now! Any help would be appreciated.
I'm not sure I go exactly your approach, but you can implement a __getattr__ method in an object that would be called when the attribute is not found:
class A(object):
def __getattr__(self, name):
print("Creating attribute %s."%name)
setattr(self, name, 'N/A')
Then:
>>> a = A()
>>> a.a
Creating attribute a.
>>> a.a
'N/A'
I don't understand the meaning of this problem or how to fix it!
I keep getting the problem AttributeError: 'list' object has no attribute 'assignmentScores'
What does this mean? and how do I fix this issue?
My code is:
class Student:
studentName = ""
studentCourse = ""
averageMark = 0
grade = "none"
assignmentScores = [1, 2, 3, 4]
def __init__(self, n, c, a, g,m):
self.studentName = n
self.studentCourse = c
self.averageMark = a
self.grade = g
self.assignmentScores = m
def getName(self):
return self.studentName
def getCourse(self):
return self.studentCourse
def getAverage(self):
return self.averageMark
def getGrade(self):
return self.grade
def getMarks(self):
return self.assignmentScores
def setAverage(self):
mark = self.averageMark
return mark
def setGrade(self):
grade = self.grade
return grade
def setMarks(self):
marks = self.setMarks()
return marks
def addMark(self):
score = list.append(self, self.assignmentScores)
def calculateAverage(self):
if len(self.assignmentScores) > 0:
average = sum(self) / float(len(self.assignmentScores))
return average
else:
return 0
def determineGrade(self):
return 0
print(calculateAverage(assignmentScores))
First, please use 4 spaces for all indentation, it helps a lot. PEP 8 is your friend and will keep everyone friendly and helpful.
As for your problem, after running the code myself and looking at the traceback, it looks like you assigned the self.assignmentScores list to self itself, so when you type self.assignmentScores you are looking up an attribute of self, which is now a list instead of an instance of the class.
This mistake comes from the way you called the method:
calculateAverage(assignmentScores)
This method only requires one argument, which is supposed to be an instance of the class Student, but not only are you calling the method directly from the class instead of from an instance, you are using the assignmentScores list as an argument for the method. This makes it so that the method calculateAverage() replaces self with self.assignmentScores so when you try to check if the list is empty the code is reading it as self.assignmentScore.assignmentScore instead of the intended way.
The way you have the class defined at the moment strongly encourages you to call the method like this.
billy = Student("","",0,"none",[1,2,3,4])
print(billy.calculateAverage())
There is another error standing in your way after you solve this problem, but a good look at the traceback and a careful reading of the relevant code will lead you to the solution. Right now all you need is a better understanding of classes and calling methods work.