Selecting a different superclass
Jason
tenax.raccoon at gmail.com
Thu Dec 18 10:20:08 EST 2008
On Dec 18, 4:36 am, "psaff... at googlemail.com"
<psaff... at googlemail.com> wrote:
> On 17 Dec, 20:33, "Chris Rebert" <c... at rebertia.com> wrote:
>
> > superclass = TraceablePointSet if tracing else PointSet
>
> Perfect - many thanks. Good to know I'm absolved from evil, also ;)
>
> Peter
Another way would be to have a factory function that builds the
appropriate instance:
class PointSet(object):
@staticmethod
def Create_Instance(*args, **keyargs):
if TRACE_DATA:
return TraceablePointSet(*args, **keyargs)
else:
return PointSet(*args, **keyargs)
# Normal release class body goes here.
class TraceablePointSet(object):
# Normal debug class body goes here
point_set = PointSet.Create_Instance()
This is the way you'd do things if you wanted a mix of your release
class instances and debug class instances. Perhaps there's only a
certain set of initial arguments that need to be checked, or maybe the
TRACE_DATA global can change. Inside the body you could also
explicitly check for a "trace" parameter, like so:
if keyargs.get( 'trace_data', False ):
# Create debug instance ....
That would allow you to create debug instances only when you want
them.
A variation on Chris Rebert's option is also possible:
class _PointSet(object):
# Normal body definition here
class _TraceablePointSet(object):
# Traceable body definition here
if TRACE_DATA:
PointSet = _TraceablePointSet
else:
PointSet = _PointSet
Hope this helps. Python's dynamic nature loves you!
--Jason
More information about the Python-list
mailing list