在Python中使用类时如何正确使用书架?

时间:2019-05-26 21:47:08

标签: python persistence pickle shelve

我正在编写一些代码来学习如何更好地使用类。我了解了程序的持久性和Python的架子。 我试图让我的用户输入一些东西,然后将它们用作我唯一类的对象。

import shelve
filearch = shelve.open('archive')
filearch['patients'] = {}

class Patient():
    def __init__(self, name='', surname='', notes=''):
        self.name = name
        self.surname = surname
        self.notes = notes

def makeone():
    print('Insert a name')
    nome = input('Nome: ')
    print('Insert a surname')
    cognome = input('surname: ')
    print('Insert notes')
    data = input('notes: ')
    a = {'name': name, 'surname': surname, 'notes': notes}
    return a
def addone():
    users_pat = Patient(**makeone())
    return users_pat

def save(user_paz):
    return filearch['patients'].update({user_paz : a)

有人可以解释一下我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

此代码中有几处要解决。

首先,由于该行无效,因此未运行,它缺少了结尾的'}'。

return filearch['patients'].update({user_paz : a)

一旦修复,就可以像这样运行代码

user = addone()
save(user)

导致此错误:

Traceback (most recent call last):
  File "test.py", line 30, in <module>
    user = addone()
  File "test.py", line 21, in addone
    users_pat = Patient(**makeone())
  File "test.py", line 18, in makeone
    a = {'name': name, 'surname': surname, 'notes': notes}
NameError: name 'name' is not defined

这是因为在makeone中,您将输入值分配给nomecognomedata,但是尝试保存不存在的变量namesurnamenotes

如果我们修复这些名称并再次运行,则会得到:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    save(user)
  File "test", line 26, in save
    return filearch['patients'].update({user_paz: a})
NameError: name 'a' is not defined

a中是您在makeone中创建的变量的名称,但是该名称仅在makeone函数内部有效。 save函数仅知道您已传递给它的user_paz变量,因此请更改

return filearch['patients'].update({user_paz : a})

return filearch['patients'].update({user_paz : user_paz})

最后,如注释中所述,您需要关闭搁置的文件以确保内容被保存。

这是您代码的改进版本:它保存输入,然后报告搁置文件的内容。

import shelve


class Patient:
    def __init__(self, name='', surname='', notes=''):
        self.name = name
        self.surname = surname
        self.notes = notes

    def __repr__(self):
        # A readable representation of a Patient object.
        return '<Patient(name={0.name}, surname={0.surname}, notes={0.notes}>'.format(self)

    # Use the same readable representation if str(patient) is called.
    __str__ = __repr__


def makeone():
    print('Insert a name')
    name = input('Nome: ')
    print('Insert a surname')
    surname = input('surname: ')
    print('Insert notes')
    notes = input('notes: ')
    a = {'name': name, 'surname': surname, 'notes': notes}
    return a


def addone():
    users_pat = Patient(**makeone())
    return users_pat


def save(user_paz):
    with shelve.open('archive') as archive:
        archive['patients'] = {user_paz.name: user_paz}
    return


def report():
    with shelve.open('archive') as archive:
        for name, patient in archive.items():
            print(name, patient)
    return


def main():
    patient = addone()
    save(patient)
    report()
    return