1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python调用子类函数_如何从一个子类调用函数到另一个子类

python调用子类函数_如何从一个子类调用函数到另一个子类

时间:2019-09-12 00:35:42

相关推荐

python调用子类函数_如何从一个子类调用函数到另一个子类

有很多方法可以实现这一点。

这里有一个:class Acct:

def __init__(self, deposit):

self.balance = deposit

# Try to avoid same names for methods and properties, unless you have a good reason for it

# Otherwise you may end up with an error like this: "TypeError: 'float' object is not callable",

# when you try to call your original balance() method

# So I renamed it to getBalance()

def getBalance(self):

print("Your balance is $",self.balance)

def getDeposit(self, deposit):

self.balance = self.balance + deposit

print("Your new balance is $",self.balance)

def getWithdraw(self, withdraw):

self.balance = self.balance - withdraw

print("Your new balance is $",self.balance)

# Transfer 'amount' from current instance to 'destination' instance

def transfer(self, amount, destination):

self.getWithdraw(amount)

destination.getDeposit(amount)

class ChkAcct(Acct):

def __init__(self, deposit):

super().__init__(deposit)

class SavAcct(Acct):

def __init__(self, deposit):

super().__init__(deposit)

# Set up the accounts and fund them

print("1. Setting accounts")

savings_account = SavAcct(100.00)

checking_account = ChkAcct(200.00)

savings_account.getBalance()

checking_account.getBalance()

# Now do the transfer

print("2. Transferring money")

savings_account.transfer(50.00, checking_account)

输出如下:

^{pr2}$

另一种方法是为此提供一个独立的函数:def transfer(amount, origin, destination):

origin.getWithdraw(amount)

destination.getDeposit(amount)

然后叫它:transfer(50.00, savings_account, checking_account)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。