[英]How to get the total value from a 2D list in inheritance?
我的目標:通過添加方法 region_total 來擴展 RegionBank 類,該方法返回該地區所有銀行的總金額。
我的問題:如何將 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)
用這個替換你的 region_total 函數:
def regional_total(self):
total = 0
for region in self.accounts:
for account in region:
total += account
return total
最后這樣稱呼它:
RBank1 = RegionalBank("Regional Bank A", 132, accounts)
print(RBank1.regional_total())
說明:Bank 類的accounts 屬性(通常稱為類屬性的變量,而參數是函數或類構造函數的輸入)是一維列表,而RegionalBank 類的accounts 屬性是二維列表(盡管它們是名稱相同),因為您只需保存帳戶,而不管它是什么維度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.