[Tutor] subclass problem: __names and type-checking
Python
python at venix.com
Sat Oct 8 19:32:26 CEST 2005
I think that a sub-class *needs* to support the same programming
interface as the parent class. Bertrand Meyer has written about
programming by contract and the implications for object oriented design.
http://archive.eiffel.com/doc/oosc/
http://se.ethz.ch/~meyer/
If B inherits from A then every context where A or an A instance appears
should work correctly with B or a B instance. Since the B constructor
*requires* more arguments, it violates that ideal. In other words, it
would be OK to allow additional arguments. It is not OK to require
them.
In other words sub-class should really be a different class that adapts
or possibly acts as a proxy for the _BaseClass. Obviously you have
picked names that presuppose inheritance.
I've abused inheritance in the past in an attempt to reuse code and have
usually regretted it. An alternative is to create a new class that
"fronts" for the class with the code we want to reuse. The __getattr__
method provides a real simple way to redirect references from our new
class to the original class.
class Base:
def __init__(self, arg1,arg2):
...
class Adapt:
def __init__(self,arg1,arg2,arg3,arg4):
self._base = Base(arg1,arg2)
...
# this provides reuse of those Base methods that can be reused directly
def __getattr__(self,attrname):
return getattr(self._base, attrname)
Without knowing more about what you are doing, I could be sending you
off in the wrong direction, but hopefully this is relevant.
--
Lloyd Kvam
Venix Corp
More information about the Tutor
mailing list