如何从父类方法访问子类方法?

问题描述 投票:0回答:3

我试图从子类继承的类中调用在子类中找到的方法。

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')

我想使用 acc_0 的信息调用函数‘add_transaction()’。不确定我是否想太多,但我该怎么办?

旁注:如果有人熟悉 rbx.lua,在这种情况下我会尝试做这样的事情:acc_0.Transactions.add_transaction(50)

python inheritance methods subclass super
3个回答
0
投票

由于您正在实例化

Account
,因此您无法访问任何事务,因为该类没有实现该功能。您需要实例化子类
Transactions
,例如:

acc_0 = Transactions('Forest Whitaker', 9)

上面的代码实际上有几个问题,但无论如何,子类化并不适合这项工作。这是一个经典的“是一个”与“有一个”面向对象问题:交易是否有帐户,不是真的。 . 交易是一种账户类型吗?不,也不对。但是,账户有交易吗?是的,它确实。因此 Transactions 的实例应该是 Account 的成员。所以:

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)

0
投票

从您想要实现的目标来看,继承层次结构是错误的。应该是相反的。

class Transactions:
  def __init__(self):
    self._transactions = []
    
  def add_transaction(self, amount):
    if not isinstance(amount, int):
      return ValueError('Please use an int.')
    self._transactions.append(amount)
    

class Account(Transactions):
  def __init__(self, full_name):
    super().__init__()
    self.full_name = full_name
    
acc_0 = Account('Forest Whitaker')

# now you can call
acc_0.add_transaction(10)

0
投票

我试图从子类继承的类中调用在子类中找到的方法。

班级帐号: def init(self, full_name): self.全名 = 全名

类交易(账户): def init(self, full_name, amount=0): super().init(全名)

self._transactions = []

def add_transaction(self, amount): 如果不是 isinstance(amount, int): return ValueError('请使用 int。') self._transactions.append(金额)

acc_0 = 交易('福里斯特·惠特克') acc_0.add_transaction(120)

© www.soinside.com 2019 - 2024. All rights reserved.