在使用Python中的类时如何正确使用工具架?

2024-10-03 09:08:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一些代码来学习如何更好地使用类。在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)

有人能解释一下我做错了什么吗?在


Tags: nameselfinputreturndefsurnameusersshelve
1条回答
网友
1楼 · 发布于 2024-10-03 09:08:47

在这段代码中有一些东西需要修正。在

首先,它没有运行,因为这行是无效的,它缺少一个结束的'}'。在

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

一旦这个问题得到解决,像这样运行代码

^{pr2}$

导致此错误:

^{3}$

{{{cd6}>和的值都是的。在

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

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

Ina是在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

相关问题 更多 >