Circular Class Logic

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Mar 14 20:58:11 EDT 2007


half.italian at gmail.com writes:

> Short of making 'Disk' no longer a subclass of Folder, is there any
> other way to include a subclassed instance in the base class of that
> object? (this is very hard to put in to words)

It's a little difficult to visualise what you're describing, but IIUC
your problem is of this form:

===== foo.py =====
import bar

class Foo(bar.Bar):
    pass
=====

===== bar.py =====
import baz

class Bar(baz.Baz):
    pass
=====

===== baz.py =====
import foo

class Baz(foo.Foo):
    pass
=====

That is, each of the classes want to inherit from the others.

The usual solution in these cases is to find the common required
functionality and factor that out to a separate class that is then the
superclass of two of the existing classes, breaking the circle.

===== wibble.py =====
# no dependencies

class Wibble(object):
    pass
=====

===== foo.py =====
import wibble
import bar

class Foo(wibble.Wibble, bar.Bar):
    pass
=====

===== baz.py =====
import wibble

class Baz(wibble.Wibble):
    pass
=====

Note that Baz no longer subclasses foo.Foo, and both Foo and Baz get
the common functionality they share from wibble.Wibble.

-- 
 \     "Buy not what you want, but what you need; what you do not need |
  `\           is expensive at a penny."  -- Cato, 234-149 BC, Relique |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list