【发布时间】:2019-03-07 23:21:35
【问题描述】:
我正在制作一个执行基本银行功能的自定义类。
class Account():
'''
A class to perform some basic banking functions
'''
UserList = {} #Empty dictionary to store (UID: name) for each new instance
def __init__(self, name, balance=0.0, uid=None):
self.name = name #The name of the account holder
self.balance = balance #The initial balance
self.uid = uid #User ID number chosen by account holder
@classmethod
def new_account(cls):
'''
New user can specify details of account through this class method via input()
'''
return cls(
input('Name: '),
int(input('Balance: ')),
int(input('UID: ')),
)
def withdraw(self, amount):
if amount > self.balance:
raise RuntimeError('Amount greater than available balance.')
else:
self.balance -= amount
return print("After a withdrawl of {}, {}'s current balance is {}".format(amount, self.name, self.balance)) #printing balance after withdrawl
def deposit(self, amount):
self.balance += amount
return print("After a deposit of {}, {}'s curent balance is {}".format(amount, self.name, self.balance)) # printing balance after deposit
基本上,新用户是通过创建Account() 类的实例来创建的,它接受名称、初始余额和用户 ID。我添加了一个类方法,以便在调用 Account.new_account() 时通过用户输入获取这些数据。我现在要做的是将每个实例(帐户)的用户 ID 和名称存储在一个空字典中。我已经玩了几个小时了,我的想法是这样的
def add_user(self, uid, name):
UserList[int(self.uid)] = self.name
插入某处,但我尝试在我的代码中的几个地方实现它,它继续只返回一个空字典。有人可以帮我指出正确的方向。此外,我正在尝试实现的另外两件事是一种防止用户选择相同 UID 的方法,以及一种要求 UID 正好是 5 个数字的方法。我对 Python 比较陌生。谢谢你。
【问题讨论】:
-
您没有正确使用静态变量。更多详情请看这里:stackoverflow.com/questions/26630821/static-variable-in-python
标签: python