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

Python类中方法调用:简易银行系统类方法运行问题

调用Python银行系统类方法的步骤

要运行你写的银行系统类方法,只需要先创建类的实例,再通过实例调用对应的方法就行,具体操作如下:

  1. 创建Bank类的实例
    因为Bank继承了User,初始化时需要传入用户名和年龄,代码示例:

    # 创建一个名为Alice、年龄25的银行用户实例
    alice = Bank("Alice", 25)
    
  2. 调用各类方法
    实例创建好后,就可以通过实例名.方法名()的方式调用方法:

    • 存款操作:传入存款金额
      alice.deposit(1000)  # 存入1000英镑
      
    • 取款操作:传入取款金额,余额不足时会提示
      alice.withdraw(300)  # 取出300英镑
      alice.withdraw(800)  # 尝试取出800英镑,会显示余额不足
      
    • 查看余额及个人信息:这个方法会自动调用父类的show_details
      alice.view_balance()
      
    • 单独查看个人信息:直接调用父类的方法
      alice.show_details()
      
  3. 完整运行示例
    把这些操作整合起来,完整代码如下:

    # 父类
    class User():
        def __init__(self,name,age):
            self.name = name
            self.age  = age
    
        def show_details(self):
            print("Personal Details")
            print("")
            print("Name ", self.name)
            print("Age  ", self.age)
    
    # 子类
    class Bank(User):
        def __init__(self,name,age):
            super().__init__(name,age)
            self.balance = 0
    
        def deposit(self,amount):
            self.amount = amount
            self.balance = self.balance + self.amount
            print("Account balance has been updated : £", self.balance)
    
        def withdraw(self,amount):
            self.amount = amount
            if self.amount > self.balance:
                print("Insufficient Funds | Balance Available : £", self.balance)
            else:
                self.balance = self.balance - self.amount
                print("Account balance has been updated : £", self.balance)
        
        def view_balance(self):
            self.show_details()
            print("Account balance: £", self.balance)
    
    # 实例化并调用方法
    if __name__ == "__main__":
        alice = Bank("Alice", 25)
        alice.deposit(1000)
        alice.withdraw(300)
        alice.view_balance()
        alice.withdraw(800)
    

运行这段代码,就能看到各个方法的执行效果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:25:19