Pregunta

Me han abierto una estantería usando el siguiente código:

#!/usr/bin/python
import shelve                   #Module:Shelve is imported to achieve persistence

Accounts = 0
Victor = {'Name':'Victor Hughes','Email':'victor@yahoo.com','Deposit':65000,'Accno':'SA456178','Acctype':'Savings'}
Beverly = {'Name':'Beverly Dsilva','Email':'bevd@hotmail.com','Deposit':23000,'Accno':'CA432178','Acctype':'Current'}

def open_shelf(name='shelfile.shl'):
    global Accounts
    Accounts = shelve.open(name)          #Accounts = {}
    Accounts['Beverly']= Beverly    
    Accounts['Victor']= Victor


def close_shelf():
    Accounts.close()

Soy capaz de agregar valores a la estantería, pero no puede modificar los valores. He definido una función de Depósitos () de la que me gustaría modificar los datos presentes en el shelve.But me da el siguiente error:

Traceback (most recent call last):
  File "./functest.py", line 16, in <module>
    Deposit()
  File "/home/pavitar/Software-Development/Python/Banking/Snippets/Depositfunc.py", line 18, in Deposit
    for key in Accounts:
TypeError: 'int' object is not iterable

Aquí está mi Función:

#!/usr/bin/python

import os                       #This module is imported so as to use clear function in the while-loop
from DB import *                       #Imports the data from database DB.py

def Deposit():
        while True:
                os.system("clear")              #Clears the screen once the loop is re-invoked
                input = raw_input('\nEnter the A/c type: ')
                flag=0
                for key in Accounts:
                        if Accounts[key]['Acctype'].find(input) != -1:
                                amt = input('\nAmount of Deposit: ')
                                flag+=1
                                Accounts[key]['Deposit'] += amt

                if flag == 0:
                        print "NO such Account!"    

if __name__ == '__main__':
        open_shelf()
        Deposit()
        close_shelf()

Soy nuevo en Python.Please me help.Correct si estoy wrong.I necesidad alguien le dé un poco de explicación sobre el funcionamiento de este code.I'm confundido.

¿Fue útil?

Solución

En primer lugar, no utilice un global de Accounts, en lugar pasarla hacia atrás y adelante. Utilizando el global causado su error. De esta manera:

def open_shelf(name='shelfile.shl'):
    Accounts = shelve.open(name)          #Accounts = {}
    ...
    return Accounts

def close_shelf(Accounts):
    Accounts.close()


def Deposit(Accounts):
    ...   

if __name__ == '__main__':
    Accounts = open_shelf()
    Deposit(Accounts)
    close_shelf(Accounts)

En segundo lugar, no se redefinen funciones integradas. En Deposit(), se asigna el resultado de raw_input a una variable llamada input:

input = raw_input('\nEnter the A/c type: ')

Cuatro líneas después, intenta utilizar la función integrada de input:

amt = input('\nAmount of Deposit: ')

Pero eso no va a funcionar porque input se ha redefinido!

En tercer lugar, cuando se itera sobre los elementos dejados de lado, siguen el patrón de 1) de agarre elemento archivado, 2) Artículo mutan, 3) de escritura mutado artículo de vuelta al estante. De esta manera:

for key, acct in Accounts.iteritems():  # grab a shelved item
    if val['Acctype'].find(input) != -1:
        amt = input('\nAmount of Deposit: ')
        flag+=1
        acct['Deposit'] += amt          # mutate the item
        Accounts[key] = acct            # write item back to shelf

(Esta tercera pequeño consejo fue ajustado de respuesta hughdbrown 's.)

Otros consejos

Creo que tendría más suerte como esto:

for key, val in Accounts.iteritems():
    if val['Acctype'].find(input) != -1:
        amt = input('\nAmount of Deposit: ')
        flag+=1
        val['Deposit'] += amt
        Accounts[key] = val
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top