nesting class definitions?

Moshe Zadka moshez at math.huji.ac.il
Mon Jan 31 19:58:16 EST 2000


On 28 Jan 2000, Neel Krishnaswami wrote:

<about inner classes>
> (Bar, Thud) is just an ordinary Python tuple -- there's nothing magic
> about them, and as long as it is tuple of classes Python is perfectly
> happy. Now, in languages with multiple inheritance, there is a style
> of defining classes called "mixins" -- you create a set of classes,
> each containing a separate capability, and then to create a class with
> all of those capabilities you define a new class that inherits from
> each mixin. (These classes are "mixed in", hence the name.)

As an idionsyncristic side note, allow me to note that I feel using mixin
classes to be a bit unclean OO design methodology. I'd prefer doing the
object method calling mechanism myself, by using composition rather then
inheritance (for example, through proxying). The only solution to using
mixin classes are places when the API is already designed, and is closed
enough so the only place one can "get through" is through inheritance. 
Even then, I'd prefer a single mixin which opened up the API through
composition.

Here's a simple way to use composition rather then inheritance:

class spam:

	def __init__(self, helpers):
		self.helpers = helpers
		self.num = num

	def use_helpers(self):
		for helper in self.helpers:
			f = getattr(helper, 'do', None)
			if f is not None:
				return f(self)

class helper1:

	def do(self, spam):
		print spam.num

class helper2:

	def do(self, spam):
		print spam.num*2

Now you can have

spam(5, helper1)
spam(6, helper2)

and even (though pointless in this example and valuable if there was
more then one method):

spam(7, helper1, helper2)

That way the method stacking is up to you, not to rather obscure (though
well defined) Python language rules.
--
Moshe Zadka <mzadka at geocities.com>. 
INTERNET: Learn what you know.
Share what you don't.





More information about the Python-list mailing list