Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'module' object has no attribute 'newperson'

Tags:

python

I am currently learning python programming (and am a beginner at it). Currently I am stuck on files exercises (so these are set things I need to do, rather than doing whatever I want. Unfortunately, it also means I probably can't do any complicated (for me) shortcuts)

Currently using Python 3.2.2

I need two different programs. One is to input what the user types in (a name and a DOB) and put that into records in a list and write that into a binary file. The other is to read that file and print that into a table using padding.

Codes:

First

    import pickle

class newperson():
    def __init__(self):
        self.name = ""
        self.dob = ""

stop = False
people = []
print("When you want to stop just hit enter")
count = 0

while stop == False:
    name = input("Please Enter the name: ")
    if len(name) == 0:
        stop = True
    else:
        people.append(newperson())
        people[count].name = name
        people[count].dob = input("Please enter their DOB: ")
        count = count + 1

file = open("ex9.4.dat", "wb")
pickle.dump(people,file)
file.close()

Second:

import pickle

myfile = open("ex9.4.dat", "rb")

people = pickle.load(myfile)

print("{0:<15}{1}".format("Name","DOB"))
for item in people:
    print("{0:<15}{1}".format(item.name,item.dob))

The problem is that I am getting the following error when trying to run the 2nd program:

AttributeError: 'module' object has no attribute 'newperson'

on

    people = pickle.load(myfile)

Unfortunately, when I have looked for answers on the other questions, either none of the solutions have worked, don't apply to me or mostly just went WAAAY over my head.

What am I doing wrong?

Thanks in advance for the help.

like image 682
PCJonathan Avatar asked Dec 17 '25 15:12

PCJonathan


1 Answers

When pickle loads the file it tries to creates newperson instances, but newpersonis not defined in the second program. To solve that problem, you could create a new file newperson.py just containing the definition of the class `newperson.py``

# newperson.py
class newperson():
    def __init__(self):
        self.name = ""
        self.dob = ""

In both programs, import the class after the import or pickle:

from newperson import newperson

Alternatively, you could use a dictionary instead of the newperson class.

like image 126
Daniel Hepper Avatar answered Dec 19 '25 04:12

Daniel Hepper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!