[英]How to get the total value from a 2D list in inheritance?
My objective: Extend the RegionalBank class by adding the method regional_total which returns the total amount of money kept in all of the banks in the region.我的目标:通过添加方法 region_total 来扩展 RegionBank 类,该方法返回该地区所有银行的总金额。
My problem: How can I put each value of 2D list on the parameter of instance RegionalBank?我的问题:如何将 2D 列表的每个值放在实例 RegionBank 的参数上?
# Do not alter this code
import sys
strings = [l.split(",") for l in sys.argv[1].split("*")]
accounts = [[int(n) for n in s] for s in strings]
class Bank:
def __init__(self, name, customers, accounts):
self.name = name
self.customers = customers
self.accounts = accounts
def branch_total(self, accounts):
total = 0
for account in accounts:
total += account
return total
# Write your code here
accounts = [
[10000, 13000, 22000],
[30000, 7000, 19000],
[15000, 23000, 31000]
]
class RegionalBank(Bank):
def __init__(self, name, customers, accounts):
super().__init__(name, customers, accounts)
def regional_total(self, accounts):
return super().branch_total(accounts)
for row,col in accounts:
print( accounts[rows][col] )
RBank1 = RegionalBank("Regional Bank A", 132, accounts)
RBank1.regional_total(accounts)
Replace your regional_total function with this:用这个替换你的 region_total 函数:
def regional_total(self):
total = 0
for region in self.accounts:
for account in region:
total += account
return total
At the end call it like this:最后这样称呼它:
RBank1 = RegionalBank("Regional Bank A", 132, accounts)
print(RBank1.regional_total())
Explanation: The accounts property (you commonly call variables of a class property, whereas parameters are the input to functions or class constructors) of the Bank class is a 1D list, but the accounts property of the RegionalBank class is a 2D list (although they are named the same), because you just save the accounts regardless of what dimention it is.说明:Bank 类的accounts 属性(通常称为类属性的变量,而参数是函数或类构造函数的输入)是一维列表,而RegionalBank 类的accounts 属性是二维列表(尽管它们是名称相同),因为您只需保存帐户,而不管它是什么维度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.