类对象中的继承不起作用,并且显示类型错误


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

def withdraw(self,amount):
self.balance-=amount
return self.balance
def deposit(self,amount):
self.balance=amount+self.balance
return self.balance
class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
BankAccount.__init__(self)
self.minimum_balance = minimum_balance

def withdraw(self, amount):
if (self.balance - amount) < (self.minimum_balance):
print('Sorry, minimum balance must be maintained.')
else:
BankAccount.withdraw(self, amount)
a=BankAccount()
a.balance
a.deposit(10)
aa=MinimumBalanceAccount(a)
aa.withdraw(1)

我得到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-179-6160646c7f5f> in <module>()
1 aa=MinimumBalanceAccount(a)
----> 2 aa.withdraw(1)
<ipython-input-168-6b59b3de5e45> in withdraw(self, amount)
5 
6     def withdraw(self, amount):
----> 7       if (self.balance - amount) < (self.minimum_balance):
8         print('Sorry, minimum balance must be maintained.')
9       else:
TypeError: '<' not supported between instances of 'int' and 'BankAccount'

我正在用这段代码修改OOP的基础知识。任何人都可以帮我清除错误。我不知道我做错了什么。为什么会出现类型错误?


您有一个看起来不错的基类BankAccount。您也可以让初始值设定项取得平衡,并将默认值设置为0。

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

def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance

您的子类中存在一些问题。首先,您尝试使用类蓝图本身而不是其实例来初始化它。您可以通过调用超类的__init__()方法来实现这一点,该方法将允许您访问它的所有属性和方法。

class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
super().__init__()
self.minimum_balance = minimum_balance

您决定覆盖继承的withdraw()方法,但尝试保留其一些原始功能。不幸的是,您不能同时使用这两种方法,因此您需要将该功能重新添加到overriden方法中。请注意,您现在可以使用self.balance从超类访问balance。

def withdraw(self, amount):
difference = self.balance - amount
if difference < self.minimum_balance:
print('Sorry, minimum balance must be maintained.')
else:
self.balance = difference
return self.balance

通过实现如上所述的类,测试的输出将产生以下结果:

a = MinimumBalanceAccount(0)
a.balance  # -> 0 (by default)
a.deposit(10)  # -> 10
a.withdraw(5)  # -> 5

编辑:

下面是子类的一个实现,它还允许您调整超类中的平衡。通过这种方式,您实际上不必在代码中的任何其他地方手动实例化BankAccount

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

def withdraw(self, amount):
difference = self.balance - amount
if difference < self.minimum_balance:
print('Sorry, minimum balance must be maintained.')
else:
self.balance = difference
return self.balance

输出如下:

a = MinimumBalanceAccount(balance=100, minimum_balance=0)
a.balance  # -> 100
a.deposit(10)  # -> 110
a.withdraw(5)  # -> 105

最新更新