You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python子类继承报错AttributeError如何修复?银行系统代码问题求解

问题修复方案

错误根本原因

你的报错核心是父类子类实例关系混淆:

  • 你初始化的C1 = Customer()是父类Customer的实例,仅包含父类__init__中定义的4个属性,本身没有子类Accounts才定义的bankdata属性
  • 你在menu方法中写的Accounts.create_account(self)是把父类实例作为self参数强行传给子类的实例方法,子类方法里访问self.bankdata自然会触发属性不存在的报错
  • 额外逻辑问题:bankdata是全银行共享的账户存储数据,不应该定义为实例属性,且你用可变对象作为__init__的默认参数,会出现所有实例共享同一份默认参数的隐藏bug

修复步骤

  1. 把bankdata调整为Accounts的类属性,所有账户操作共享同一份存储,也方便后续其他类继承Accounts时直接访问该属性
  2. 直接实例化子类Accounts调用menu方法,不需要单独实例化父类Customer,因为Accounts继承了父类所有属性和方法
  3. 修正类继承逻辑和方法调用逻辑,避免父类实例调用子类独有属性

修复后完整代码

from random import randrange
from secrets import randbelow
import collections
import time

class Customer:
    def __init__(self, Fname = "Please enter your First name:", Lname = "Please enter your Last name:", email = "Please enter your email:",  balance = 0):
        self.Fname = Fname 
        self.Lname = Lname 
        self.email = email
        self.balance = balance
      
    def menu(self):
        print ("-----------------------------------------------")
        print("Welcome to Dangote's Wellings Bank")
        print ("-----------------------------------------------")
        print("1.Create an account \n2.Log in to your acccount \n3.Exit")
        menu_option = int(input())
        if menu_option == 1:
            self.create_account()
        if menu_option == 2:
            self.log_in()
        if menu_option == 3:
            self.exit_bank()

class Accounts(Customer):
    # 全局银行账户数据,定义为类属性,所有实例共享
    bankdata = collections.defaultdict(dict)
    def __init__(self):
        super().__init__()

    def create_account(self):
        print("\n")
        firstname = input(self.Fname)
        lastname = input(self.Lname)
        global account_name
        account_name = firstname + " " + lastname
        input(self.email)
        
        card_number = f'400000{randrange(1e10):010}'
        pin_request = input("Would you like the bank to issue your unique PIN or create your PIN yourself (Issue/Create): ")

        if pin_request == "Issue":
            pin_number = f'{randbelow(10_000):04}'
        elif pin_request == "Create":
            pin_number = input("Enter your desired 4 DIGIT PIN: ")
        else:
            print("Invalid Input please try again")
            self.create_account()

        print(f'\nYour card has been created\nAccount Name:\n{account_name} \nYour card number:\n{card_number}\nYour card PIN:\n{pin_number}')
        # 此处访问类属性bankdata
        self.bankdata[account_name][card_number] = pin_number
        print(self.bankdata)
        print("\nYou can now log in")
        self.menu()

    def log_in(self):
        global card_no, card_pin
        for key, value in self.bankdata.items():
            if isinstance(value, dict):
                for card_no, card_pin in value.items():
                    if key == account_name:
                        global card_login
                        card_login = input("Enter your card number: ")
                        pin_login = input("Enter your PIN: ")

        if card_login == card_no and pin_login == card_pin:
            print(f'\nYou have successfully logged in')
            # 这里你后续补充Bankingsystem类即可正常调用
            # Bankingsystem.operation_to_perform(self)
        else:
            print("\n Wrong Card or PIN!")
            time.sleep(2)
            self.menu()

    def log_out(self):
        print("You have successfully logged out")
        self.menu()
    def exit_bank(self):
        print("Thanks for banking with us, we hope to see you next time. Bye!")

# 直接实例化子类Accounts,继承了父类的menu方法,正常触发流程
C1 = Accounts()
C1.menu()

效果说明

运行代码后创建账户即可正常打印bankdata字典,后续其他类继承Accounts后可直接通过self.bankdata访问到全局的账户存储数据。

内容的提问来源于stack exchange,提问作者Weke Moyosore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:36:03