【问题标题】:How do you call a parent class's method within a dictionary created in the child class?如何在子类中创建的字典中调用父类的方法?
【发布时间】:2020-06-11 18:34:42
【问题描述】:

我正在处理一个关于继承和银行账户的项目,我在其中定义了一个父类和子类(分别为 Account 和 Checking_Account)。

Checking_Account 包含一个静态字典,将字符串映射到称为“选项”的函数。有些函数定义在子类Checking_Account中,有些函数定义在父类Account中。

例如,

options = {"See Number of Remaining Checks" : _remainingChecks,
           "View Balance" : super()._viewBalance}

但是,这会返回错误

Traceback (most recent call last):
  File "/Users/dawsonren/Documents/ASWDV/Python/Accounting/account_SO.py", line 24, in <module>
    class Checking_Account(Account):
  File "/Users/dawsonren/Documents/ASWDV/Python/Accounting/account_SO.py", line 33, in Checking_Account
    "View Balance" : super()._viewBalance()}
RuntimeError: super(): no arguments

这是一个最小的可复制示例。

class Account(object):
    def __init__(self, name, bal):
        """(str, float) => Account object

        Instantiates the Account object.

        """
        self.name = name
        self.balance = bal

    def viewBalance(self):
        print(f"Account has ${self.balance}.")

    def run(self, options):
        """{str : function} => None
        Runs the function based on the input of the user.
        """

        for key in options.keys():
            print(key)
        select = input("Type the option you want.")
        options[select]()

class Checking_Account(Account):
    def __init__(self, name, bal, checks = 100):
        super().__init__(name, bal)
        self.checks = checks

    def remainingChecks(self):
        print(f"Account {self.num} has {self.checks} checks.")

    options = {"See Number of Remaining Checks" : remainingChecks,
               "View Balance" : super().viewBalance}

    def run(self):
        super().run(Checking_Account.options)

这是我作为一名高中生在这里的第一篇文章,所以我可以使用我能获得的任何帮助。如果我所做的不是最佳实践,请指出正确的方法!

【问题讨论】:

  • 请注意,super 真的很神奇:它用两个参数定义,但它们没有默认值。相反,编译器会根据调用它的上下文(需要在方法内部)生成缺少的参数。
  • 父类依赖父类中未明确定义的任何内容也是一个坏主意。
  • 与获取用户输入并作为结果执行某些操作相关的代码不属于 Account 类,它应该模拟银行账户,而不是使用银行的行为。跨度>
  • 感谢您的帮助!我一定会实现这些。

标签: python python-3.x dictionary inheritance methods


【解决方案1】:

我想你在面向对象编程中有关于继承的课程,或者至少读过它?

在这里,您的类 Checking_Account 继承自 Account,因此这意味着它继承了它的方法等。

因此无需尝试拨打super().viewBalance,您只需拨打self.viewBalance()即可。

【讨论】:

  • 您好 Antoine 先生,我明白您的回答,并且我已尝试通过这些更改运行示例。然而,我得到了一个 NameError: ‘self’ is not defined。我的理解是 self 只能在实例方法中调用——我做错了什么吗?非常感谢您的回答,非常感谢!
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 2020-01-14
  • 1970-01-01
  • 2014-08-24
相关资源
最近更新 更多