【问题标题】:How to access a subclass method from parent method?如何从父方法访问子类方法?
【发布时间】:2021-07-09 02:21:26
【问题描述】:

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

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)

【问题讨论】:

  • 这不是继承的目的。 Account 的具体实例没有 add_transaction 方法,因为它不是 Transaction。您创建的继承层次结构说“每笔交易都是一个帐户”,但不是相反
  • acc_0 = Account('Forest Whitaker', '12/9/2000', 9) 应该给您一个错误,请尝试改用 Transactions 类

标签: python inheritance methods subclass super


【解决方案1】:

从您想要实现的目标来看,继承层次结构是错误的。那应该是另一种方式。

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)

【讨论】:

  • 欣赏一下。
【解决方案2】:

由于您正在实例化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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2014-10-04
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多