I currently implementing a class called BankAccount
. It offers the ability to set a balance, make a deposit, make a withdrawal, and check the balance.
我目前正在实现一个名为BankAccount的类。它提供了设置余额、存款、取款和检查余额的能力。
Now I have to write a function (called processAccounts()
) that will take the name of a file as its parameter. The first line of the file will be a number which specified the initial bank account balance. The lines that follow will specify a series of withdrawals and deposits marked by w
or W
for withdrawals and d
or D
for deposits. The function must read the the text file, set the initial balance, and then make withdrawals or deposits based on the contents of the text file.
现在我必须编写一个函数(名为processAccounts()),它将文件的名称作为参数。文件的第一行将是指定初始银行账户余额的数字。接下来的行将指定一系列以w或w标记的取款和存款,d或d标记的存款。函数必须读取文本文件,设置初始余额,然后根据文本文件的内容提取或存款。
Here is what I have so far:
这是我到目前为止所得到的:
class BankAccount:
def set(self,balance=0):
self.balance=balance
def deposit(self,amount):
self.balance += amount
def withdraw(self,amount):
self.balance -= amount
def get_balance(self):
return self.balance
def processAccounts(fname):
with open(fname,'r') as f:
acct=[]
for line in f:
line=line.split()
if line:
line= [int(i) for i in line]
acct.set(line)
Text File:
文本文件:
1000.00
W 50.50
W 5.25
d 100.75
w 525.15
d 85.70
I am currently trying to set up the first part which will read the first line and then call upon the set()
function to set the initial balance.
我目前正在尝试设置第一部分,它将读取第一行,然后调用set()函数来设置初始平衡。
The error I'm getting is:
我得到的错误是:
ValueError: invalid literal for int() with base 10: '1000.00'
Am I approaching this problem incorrectly or did I just not do it correctly?
我是错误地解决了这个问题还是我做错了?
3 个解决方案
#1
8
The general approach is correct, but int
is clearly wrong since apparently the amounts are expressed in "dollars.cents".
一般的方法是正确的,但int显然是错误的,因为金额显然是用“dollar .cents”表示的。
float
would appear to work but would probably not be the right choice: handling monetary amounts is instead the primary reason the decimal
module was added to the Python standard library! With decimal
you'll get precise computations, without the risk of rounding errors losing or gaining a cent here and there which would unchain The Auditors upon you.
float看起来很有用,但它可能不是正确的选择:处理货币数量是将小数模块添加到Python标准库的主要原因!有了十进制之后,您将得到精确的计算,而不会有四舍五入错误的风险,也不会在这里或那里损失一分钱,从而将审计人员从您身上解放出来。
So here's how I'd do it...:
下面是我的做法……
import decimal
class BankAccount:
def set(self,balance=decimal.Decimal('0.00'):
self.balance = balance
# the rest of the class is fine. Shd probably have an __init__ tho.
# also should keep an audit trail of deposit and withdrawals!
def processAccounts(fname):
with open(fname,'r') as f:
start_bal = decimal.Decimal(next(f).strip())
ba = BankAccount()
ba.set(start_bal)
for line in f:
fields = line.strip().split()
if fields:
if fields[0] in 'Ww':
ba.withdraw(decimal.Decimal(fields[1])
elif fields[0] in 'Dd':
ba.deposit(decimal.Decimal(fields[1])
else:
print('Ignoring line: {!r}'.format(line.strip()))
return ba
#2
0
First, since you are working with money the correct answer is to use the decimal
class as suggested by Alex Martelli.
首先,由于您使用的是货币,正确的答案是使用Alex Martelli建议的十进制类。
Having said that, the answer to the specific problem of the ValueError
can be solved with a 3rd party module called fastnumbers (I am the author). It provides a function called fast_forceint
that will corerce strings of floats to (i.e. '1000.00') to an int
.
尽管如此,对于ValueError的具体问题的答案可以通过一个名为fastnumbers的第三方模块来解决(我是作者)。它提供了一个名为fast_forceint的函数,它将corerce字符串连接到浮点数(即:“1000.00”)int。
>>> from fastnumbers import fast_forceint
>>> fast_forceint('1000.00')
1000
>>> isinstance(fast_forceint('1000.00'), int)
True
This library was specifically designed to ease the pain of converting strings to numeric types.
这个库是专门为减轻将字符串转换为数字类型的痛苦而设计的。
#3
0
To do so without using the decimal class (less accurate when working with floats), also including a constructor:
不使用decimal类(使用浮点数时更不精确),也包括构造函数:
class BankAccount():
def __init__(self, initialBalance = 0):
self.accBalance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self.accBalance))
def set(self, amount):
self.accBalance = amount
def deposit(self, amount):
self.accBalance += amount
def withdraw(self, amount):
self.accBalance -= amount
def balance(self):
return(self.accBalance)
def processAccount(filename ):
with open(filename,'r') as f:
b = BankAccount()
startBal = f.readline().split()
startBal = float(startBal[0])
b.set(startBal)
for line in f:
fields = line.strip().split()
if fields[0] in 'Ww':
b.withdraw(float(fields[1]))
elif fields[0] in 'Dd':
b.deposit(float(fields[1]))
return b
#1
8
The general approach is correct, but int
is clearly wrong since apparently the amounts are expressed in "dollars.cents".
一般的方法是正确的,但int显然是错误的,因为金额显然是用“dollar .cents”表示的。
float
would appear to work but would probably not be the right choice: handling monetary amounts is instead the primary reason the decimal
module was added to the Python standard library! With decimal
you'll get precise computations, without the risk of rounding errors losing or gaining a cent here and there which would unchain The Auditors upon you.
float看起来很有用,但它可能不是正确的选择:处理货币数量是将小数模块添加到Python标准库的主要原因!有了十进制之后,您将得到精确的计算,而不会有四舍五入错误的风险,也不会在这里或那里损失一分钱,从而将审计人员从您身上解放出来。
So here's how I'd do it...:
下面是我的做法……
import decimal
class BankAccount:
def set(self,balance=decimal.Decimal('0.00'):
self.balance = balance
# the rest of the class is fine. Shd probably have an __init__ tho.
# also should keep an audit trail of deposit and withdrawals!
def processAccounts(fname):
with open(fname,'r') as f:
start_bal = decimal.Decimal(next(f).strip())
ba = BankAccount()
ba.set(start_bal)
for line in f:
fields = line.strip().split()
if fields:
if fields[0] in 'Ww':
ba.withdraw(decimal.Decimal(fields[1])
elif fields[0] in 'Dd':
ba.deposit(decimal.Decimal(fields[1])
else:
print('Ignoring line: {!r}'.format(line.strip()))
return ba
#2
0
First, since you are working with money the correct answer is to use the decimal
class as suggested by Alex Martelli.
首先,由于您使用的是货币,正确的答案是使用Alex Martelli建议的十进制类。
Having said that, the answer to the specific problem of the ValueError
can be solved with a 3rd party module called fastnumbers (I am the author). It provides a function called fast_forceint
that will corerce strings of floats to (i.e. '1000.00') to an int
.
尽管如此,对于ValueError的具体问题的答案可以通过一个名为fastnumbers的第三方模块来解决(我是作者)。它提供了一个名为fast_forceint的函数,它将corerce字符串连接到浮点数(即:“1000.00”)int。
>>> from fastnumbers import fast_forceint
>>> fast_forceint('1000.00')
1000
>>> isinstance(fast_forceint('1000.00'), int)
True
This library was specifically designed to ease the pain of converting strings to numeric types.
这个库是专门为减轻将字符串转换为数字类型的痛苦而设计的。
#3
0
To do so without using the decimal class (less accurate when working with floats), also including a constructor:
不使用decimal类(使用浮点数时更不精确),也包括构造函数:
class BankAccount():
def __init__(self, initialBalance = 0):
self.accBalance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self.accBalance))
def set(self, amount):
self.accBalance = amount
def deposit(self, amount):
self.accBalance += amount
def withdraw(self, amount):
self.accBalance -= amount
def balance(self):
return(self.accBalance)
def processAccount(filename ):
with open(filename,'r') as f:
b = BankAccount()
startBal = f.readline().split()
startBal = float(startBal[0])
b.set(startBal)
for line in f:
fields = line.strip().split()
if fields[0] in 'Ww':
b.withdraw(float(fields[1]))
elif fields[0] in 'Dd':
b.deposit(float(fields[1]))
return b