Q on use of Class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Q on use of Class (/thread-25539.html) |
Q on use of Class - ebolisa - Apr-02-2020 Hi, The code below runs as designed when executed the first time. It creates a file with binary data. Because on the first run the file doesn't exist, a warning is printed. However, the same warning is printed when the code is executed a second time. I don't understand why the warning it shoed the second time when the file does have data. Any help is appreciated. TIA import pickle class People: def __init__(self, name, gender, age): self.name=name self.gender=gender self.age=age print("A new person has been added with the name of: ", self.name) def __str__(self): return "{} {} {}".format(self.name, self.gender, self.age) class PeopleList: people=[] def __init__(self): listOfPeople=open("externalFile", "ab+") #reset cursor position listOfPeople.seek(0) #just in case on the first run the file is empty try: self.people(pickle.load(listOfPeople)) print("{} people have been loaded".format(len(self.people))) except: print("The file is empty") finally: listOfPeople.close() #del(listOfPeople) def addPeople(self, p): self.people.append(p) self.savePeopleToFile() def showPeople(self): for p in self.people: print(p) def savePeopleToFile(self): listOfPeople=open("externalFile", "wb") pickle.dump(self.people, listOfPeople) listOfPeople.close() del(listOfPeople) def showExternalFileInfo(self): print("File info:") for p in self.people: print(p) myList=PeopleList() p=People("Roman", "male", 59) myList.addPeople(p) #p=People("Mike", "male", 29) #myList.addPeople(p) #p=People("Rosa", "female", 48) #myList.addPeople(p) #p=People("Maria", "female", 28) #myList.addPeople(p) myList.showExternalFileInfo() RE: Q on use of Class - buran - Apr-02-2020 don't use all-catching except - you cannot see what actual error is. In this case self.people(pickle.load(listOfPeople))self.people is a list and it's not callable. RE: Q on use of Class - ebolisa - Apr-02-2020 Thanks. I was missing '=' in that line. Fixed it with self.people=pickle.load(listOfPeople) |