[Tutor] design questions: pythonic approach to ostriches

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Apr 24 04:16:41 CEST 2005



> I do remain a bit surprised that there seems to be no way to implement
> what I naively thought would be the obvious solution -- to remove an
> inherited method from the instance's dictionary.


Hi Brian,

If we're trying to do this, we probably don't want to "inherit" from a
parent.  A subclass child is supposed to have, at the very least, the same
public methods as its parent.  For example, if we have a:

######
class Account:
    def __init__(self, amount):
        self.amount = amount

    def withdraw(self, x):
        assert x > 0
        self.amount = self.amount - x

    def report(self):
        print "You have ", self.amount, "dollars"
#######


And we'd like to reuse this, but for something that doesn't report itself,
we shouldn't use inheritance:

#######
class SecretAccount(Account):
    def report(self):
        pass
#######


This SecretAccount is now pretending to be an account that doesn't have a
usable report() method.

#######
>>> Account(5).report()
You have  5 dollars
>>> SecretAccount(5).report()
>>>
#######



But we can get into trouble again, if, later on, Account is expanded to
have a few more additional functions:

######
class Account:  ## version 2
    # [same as before]
    def htmlReport(self):
        print ("<html><body><p>You have %d dollars</p></body></html" %
                self.amount)
######

And now, suddenly, SecretAccount again has a method that shows information
that it probably doesn't want out in the open.


The issue that that SecretAccount is really not trying to be an "Account":
it's just trying to reuse its functionality.  Instead of doing things with
inheritance, we're probably looking for delegation:

#######
class SecretAccount:
    def __init__(self, amount):
        self.account = Account(amount)
    def withdraw(self, x):
        self.account.withdraw(x)
#######

And now we're more isolated from changes to the Account class.


There are some more Pythonic idioms to make delegation easier to code.
And the example above is hideously toyish.  *grin*

But I hope the idea's a little clearer: inheritance ties the subclass down
to at least what the superclass has promised, and in many cases, that's
not what we want.


Best of wishes!



More information about the Tutor mailing list