[Tutor] design questions: pythonic approach to ostriches

Brian van den Broek bvande at po-box.mcgill.ca
Sun Apr 24 08:27:11 CEST 2005


Danny Yoo said unto the world upon 2005-04-23 22:16:
> 
>>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:


<SNIP e.g. of an account class with report method and a subclass 
SecretAccount which overrides the report method to do nothing>


> 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.


Thanks Danny, that's really helpful.

I still think the "delete an inherited method" approach could be 
useful in some cases, but your example certainly shows it would come 
with its own sack of troubles, too. Given that it would take a 
language change, and wouldn't be less troubled than any of the other 
available approaches, I can now happily agree that it wouldn't be 
worth it.

Best to all,

Brian vdB



More information about the Tutor mailing list