python - 如何在子类中创建的字典中调用父类的方法?
问题描述
我正在做一个关于继承和银行账户的项目,我在其中定义了一个父类和子类(分别是 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)
这是我作为高中生的第一篇文章,所以我可以使用我能得到的任何帮助。如果我正在做的不是最佳实践,请指出正确的方法!
解决方案
我想你在面向对象编程中有关于继承的课程,或者至少读过它?
在这里,您的类Checking_Account
继承自Account
,因此这意味着它继承了它的方法等。
所以无需尝试调用super().viewBalance
,您只需调用即可self.viewBalance()
。
推荐阅读
- c# - Alglib 卡方分布示例
- javascript - 为什么我确实有以下类型错误:无法读取未定义的属性“长度”?(在反应中)
- android - 记住 LazyColumn 滚动位置 - Jetpack Compose
- webrtc - 特定对等方的 STUN 绑定(ICE 连接检查)失败
- neovim - 如何更改 coc.nvim 中 pylint 的路径?
- javascript - 尝试在 React Native 中更新数组对象
- ssis - 如果进程今天已经运行,如何禁用任务
- php - 以下代码未达到 else 语句
- java - 如何使用 jsoup 从网站获取视频或音频的 URL
- lua - 如何在 theme.lua/rc.lua (AwesomeWM) 中禁用窗口边框