简体   繁体   中英

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.

My problem: How can I put each value of 2D list on the parameter of instance RegionalBank?

# 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM