Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Q on use of Class
#1
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()
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thanks. I was missing '=' in that line. Fixed it with
self.people=pickle.load(listOfPeople)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020