[Tutor] Method overriding

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 16 Mar 2001 00:01:14 -0800 (PST)


On Thu, 15 Mar 2001 jovoslav@dir.bg wrote:

> Hello,
> Can someone please define what method overriding means.

Sometimes I get the terminology all mixed up; I'll assume you want to use
inheritence to override the definition of an older class.  Let's take the
venerable Account class as an example of using method overriding:

###
>>> class Account:
...     def __init__(self, balance):
...         self.balance = balance
...     def withdraw(self, amount):
...         self.balance = self.balance - amount
...     def __str__(self):
...         return 'balance: %s' % self.balance
...
>>> x = Account(42)
>>> x.withdraw(-10)
>>> print x
balance: 52  
###


Hmmm... that's quite interesting!  We can withdraw negative amounts of
money for profit!  Let's say that we want to disallow negative withdrawals
from an account.  What we can do is take our preexisting Account class,
and slightly tweak it: let's override the definition of withdraw() to be a
little more stringent:

###
>>> class RestrictedAccount(Account):
...     def __init__(self, balance):
...         Account.__init__(self, balance)
...     def withdraw(self, amount):
...         if amount < 0:
...             print "Bad!  Bad!"
...         else:
...             Account.withdraw(self, amount)
... 
>>> x = RestrictedAccount(42)
>>> x.withdraw(5)
>>> print x
balance: 37
>>> x.withdraw(-1000)
Bad!  Bad!
###


Hope this helps!