【问题标题】:fix the error of File " line 1, in <module> NameError: name 'Account' is not defined修复 File " line 1, in <module> NameError: name 'Account' is not defined 的错误
【发布时间】:2021-04-19 21:06:41
【问题描述】:

我在 Python 中在线运行这些代码,但收到错误消息“文件”,第 1 行,在 NameError: name 'Account' is not defined';我想知道如何在那里定义“帐户”?多谢!这是我的第一个 Python 代码。

class SavingAccount(Account):
 def _init_(self, holder_name, saving_rateaccount_number=None):   
    super()._init_(holder_name, account_number) 
    self.saving_rate = saving_rate
def _repr_(self): 

return 'SavingAccount('+str(self.holder_name)+', '+str(self.saving_rate)+', '+str(self.account_number)+')'
saving_account=SavingAccount('saving_1', 0.02)
print(saving_account)

【问题讨论】:

  • 你有一个叫Account的类吗?它是否在您的子类“SavingAccount”之上
  • 其实这是我班的一个作业,老师问“代码会打印什么”,所以我在这里programiz.com/python-programming/online-compiler在线尝试了代码并得到了错误。
  • 顺便说一句,我想知道如何使它工作,我的意思是如何定义父类(?)。非常感谢您的帮助!
  • 没错,所以您不能复制该代码并尝试运行它,您需要另一个名为 Account 的 arent 类。您应该研究继承和类。 programiz.com/python-programming/inheritance

标签: python


【解决方案1】:

如果您在另一个 Python 文件中定义类 Account,则必须在 class SavingAccount(Account): 之前添加 from other_file import Account 才能使其工作。

【讨论】:

    【解决方案2】:

    当你这样做时:

    class My_class ( Other_class ):
        def __init__(self,...):
            # code lines
        def my_method(self,...):
            # more code
    

    这意味着My_class对象会继承Other_class的方法和属性,所以你必须先定义Other_class才能在My_class中使用它。总之,新类将拥有自己的方法和属性以及Other_class 方法和属性。

    例子:

    class Other_class():
        def __init__(self,...):
            # constructor code lines
        def other_method(self,...):
            # more code lines 
    
    class My_class( Other_class ):
        def __init__(self,...):
            # other constructor code lines
        def my_method(self,...):
            # some more code lines
    

    你可以找到完整的信息in Python documentation

    PS:我的建议是经常看官方文档,你甚至可以发现更多的想法和扩展你的语言知识。顺便说一下,你会看到 Python 有多么有用,继续努力吧?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-07
      • 2022-11-27
      • 1970-01-01
      相关资源
      最近更新 更多