我目前正在编写一个银行应用程序,下面您可以看到我的代码:
from customer import Customer
from exceptions import KeyError
class Bank(object):
""" All the bank operations are contained in this class e.g customer Registration """
def __init__(self, name):
self.name = str(name)
self.customers = dict()
self.registration_customer(name)
def registration_customer(self, name):
""" Registration of a new user to the bank
Args:
name (str): name of the customer
"""
name = str(name)
if not self.customers.get(name, None):
self.customers[name] = Customer(name)
def close_customer_account(self, name, account_type):
""" close an account of a customer by name and account_type
Args:
name (str) : name of the account holder
account_type (str) : type of account
"""
name = str(name)
account_type = str(account_type)
customer = self.customers.get(name, None)
if customer:
customer.close_account(account_type)
def get_customer_info(self, name):
""" get customer info
Args:
name (str) : name of the customer
"""
if not self.customers[name]:
raise KeyError('I am sorry! Customer does not exist')
return self.customers[name]
引发错误
如果您看到 get_customer_info
函数,并且 name
不存在,那么我将引发错误
。假设银行应用程序非常关键,这是我在 Python 中引发错误
的最佳方法吗?您还可以假设这是生产级别的代码。
def get_customer_info(self, name):
""" get customer info
Args:
name (str) : name of the customer
"""
if not self.customers[name]:
raise KeyError('I am sorry! Customer does not exist')
return self.customers[name]
最佳答案
我认为这取决于软件的需求。 理想情况下,应在提交表单之前告知用户其输入无效,使提交按钮变灰并提示输入用户名。
如果提交,应记录该错误,以便生成统计数据,如果这是一个非常严重或不寻常的错误,则应自动生成电子邮件并发送给相关人员。
用户应该被重定向回输入表单并且他们之前提交的信息仍然完好无损,不要强制用户重新提交整个表单。
关于python - 在 Python 中引发错误的一种非常优雅的方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34712812/