Mixin classes and single/multiple inheritance
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Sep 20 05:25:04 EDT 2007
On Thu, 20 Sep 2007 14:52:50 +1000, Ben Finney wrote:
> Can you give a code example of how you think mixins should be
> implemented in Python, assuming the absence of multiple inheritance?
I'll take a shot at it... use automatic delegation to the mixin class.
class Parrot(object):
def fly(self):
return "The parrot can fly short distances."
def talk(self):
return "I'm pining for the fjords."
class Albatross(object):
def fly(self):
return "The albatross is known to fly enormous distances."
# Now I want a talking Albatross, without using multiple inheritance.
class TalkingAlbatross(Albatross):
def __init__(self, *args, **kwargs):
# avoid triggering __setargs__
self.__dict__['mixin'] = Parrot()
# avoid using super() so Ben doesn't get cranky
self.__class__.__base__.__init__(self, *args, **kwargs)
def __getattr__(self, name):
return getattr(self.mixin, name)
def __hasattr__(self, name):
return hasattr(self.mixin, name)
def __delattr__(self, name):
return delattr(self.mixin, name)
def __setattr__(self, name, value):
return setattr(self.mixin, name, value)
Am I close?
--
Steven.
More information about the Python-list
mailing list