首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AttributeError在我的python代码2中

AttributeError在我的python代码2中
EN

Stack Overflow用户
提问于 2015-12-14 12:55:45
回答 1查看 832关注 0票数 1

我在python中有以下代码行:

代码语言:javascript
复制
class BankAccount:
  def __init__ (self,balance = 0):
    self.balance = balance

    def deposit(self, deposit_amount= 30):
      self.deposit_amount=deposit_amount
      balance += deposit_amount
      return balance

      def withdraw (self,withdraw_amount= 10):
        if withdraw_amount > balance:
          raise RuntimeError('Invalid Transaction')
          balance -= withdraw_amount
          return balance

          class MinimumBalanceAccount(BankAccount):
            def __init__(self,balance = 0):
              self.balance = balance

              c = BankAccount()
              c.deposit(50)

它给了我这个错误:

代码语言:javascript
复制
AttributeError("BankAccount instance has no attribute 'deposit'"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-14 12:59:17

如果您的缩进实际上是发布的,那么deposit函数是在__init__方法中定义的。因此,它不是类的属性,而只是__init__方法中可用的函数。下面的代码只是代码的副本,但是缩进是固定的:

代码语言:javascript
复制
class BankAccount:
    def __init__(self,balance=0):
        self.balance = balance

    def deposit(self, deposit_amount=30):
        self.deposit_amount=deposit_amount
        self.balance += deposit_amount
        return self.balance

    def withdraw(self,withdraw_amount=10):
        if withdraw_amount > self.balance:
            raise RuntimeError('Invalid Transaction')
        self.balance -= withdraw_amount
        return self.balance

class MinimumBalanceAccount(BankAccount):
    def __init__(self,balance = 0):
        self.balance = balance

c = BankAccount()
c.deposit(50)

这段代码适用于我,就像我用c = MinimumBalanceAccount()替换c = MinimumBalanceAccount()时一样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34267622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档