Search code examples
pythoninheritancemethodssubclasssuper

How to access a subclass method from parent method?


I’m trying to call a method found within a subclass from the class it inherits from.

class Account:
  def __init__(self, full_name):
    self.full_name = full_name
    
class Transactions(Account):
  def __init__(self, full_name, amount=0):
    super().__init__(full_name)
    
    self._transactions = []
    
  def add_transaction(self, amount):
    if not isinstance(amount, int):
      return ValueError('Please use an int.')
    self._transactions.append(amount)
    
acc_0 = Account('Forest Whitaker')

I want to call the function ‘add_transaction()’ using acc_0’s info. Not sure if I’m overthinking but how would I go about this?

sidenote: if anyone is familiar with rbx.lua, in this situation I’d be trying to do something like this: acc_0.Transactions.add_transaction(50)


Solution

  • Since you are instantiating an Account, you can't access any transactions, because that class doesn't implement that functionality. You would need to instantiate the subclass Transactions, eg:

    acc_0 = Transactions('Forest Whitaker', 9)
    

    There are actually several problems with your code above, but the subclassing isn't really right for this job anyway.. it's a classic "is a" vs "has a" object oriented problem: Do transactions HAVE an account, not really.. Is transactions a type of account?? No, not right either. But, does an account HAVE transactions? Yes, it does. So an instance of Transactions should be a member of Account. So:

    class Account:
      def __init__(self, full_name):
        self.full_name = full_name
        self.transactions = Transactions()
    
    class Transactions:
      def __init__(self):
        super().__init__()
        
        self._transactions = []
        
      def add_transaction(self, amount):
        if not isinstance(amount, int):
          return ValueError('Please use an int.')
        self._transactions.append(amount)
        
    acc_0 = Account('Forest Whitaker')
    acc_0.transactions.add_transaction(9)