Reputation: 113
Say I have two container classes that behave slightly differently, but have a lot of common methods. I use a mixin class to add these methods to both containers.
For example:
class SpamContainer(Mixin, BaseClass):
def __init__(self, spam):
super(SpamContainer, self).__init__(spam)
class DifferentSpamContainer(Mixin, DifferentBaseClass):
def __init__(self, spam):
super(DifferentSpamContainer, self).__init__(spam)
class Mixin(object):
# has no __init__()
def useful_method(self):
for s in self.spam:
# do something
Now I want to add a new method to Mixin
that creates and returns a new container object - if self
is a SpamContainer
, I want to create one of those, whereas if it's a DifferentSpamContainer
, I want to create one of those. How can I call the correct constructor from within a method of Mixin
?
I thought maybe I could use something like this:
class Mixin(object):
def method(self, spam):
return self.__init__(spam)
or
class Mixin(object):
def another_method(self, spam):
return self.__class__(spam)
but I can't get it to work.
I'm using python 2.7.
Upvotes: 1
Views: 1650
Reputation: 309929
You use a classmethod
:
class Mixin(object):
@classmethod
def alternate_constructor(cls, spam):
return cls(spam)
Note that your use of mixins here seems to be a little off. Frequently, when using inheritance (single or multiple), you'll want to call up to the method on the base-class. e.g. in your case, Mixin
and the various classes that it is being mixed with can't both have their constructors called. In fact, you aren't even calling __init__
in BaseClass
for SpamContainer
for example. This is a bit strange. If you're going to be doing any work with multiple inheritance, I strongly suggest you read Super Considered Super! and companion article Super considered harmful. This will help you to know the pitfalls of multiple inheritance (and how to avoid them).
Upvotes: 3