Python Shelve无法检索对象

时间:2012-06-04 04:16:34

标签: python

我试图存储物品并且能够成功地完成它。但是我遇到了问题,而在处理它时..错误在下面给出

person.py

class Person:
    def __init__(self, name, age, pay=0, job=None):
        self.name = name
        self.age  = age
        self.pay  = pay
        self.job  = job

    def lastname(self):
        return  self.name.split()[-1]

    def giveraise(self,percent):
        #return self.pay *= (1.0 + percent)
        self.pay *= (1.0 + percent)
        return self.pay

Manager.py

from Person import Person

class Manager(Person):
    def giveRaise(self, percent, bonus=0.1):
        self.pay *= (1.0 + percent + bonus)        
        return self.pay

update_db_classes.py

import shelve
from Person import Person
from Manager import Manager
bob = Person('Bob Smith', 42, 30000, 'software')
sue = Person('Sue Jones', 45, 40000, 'hardware')
tom = Manager('Tom Doe',  50, 50000)

db = shelve.open('class-shelve')
db['bob'] = bob
db['sue'] = sue
db['tom'] = tom
db.close()

检索对象的代码.. dump_db_classes.py

import shelve
db = shelve.open('class-shelve')
for key in db:
    print(key, '=>\n  ', db[key].name, db[key].pay)

bob = db['bob']
print(bob.lastName())
print(db['tom'].lastName())

错误: C:\ Python27 \基础> dump_db_classes.py bob =>    鲍勃史密斯30000 sue =>    苏琼斯40000 tom =>    Tom Doe 50000 Traceback(最近一次调用最后一次):   文件“C:\ Python27 \ Basics \ dump_db_classes.py”,第8行,in     打印(bob.lastName()) AttributeError:'Person'对象没有属性'lastName'

1 个答案:

答案 0 :(得分:1)

Python区分大小写。您拨打bob.lastName()Person方法为.lastname()。错误消息试图告诉您:

AttributeError: 'Person' object has no attribute 'lastName'