473,386 Members | 1,962 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Need advice on subclassing code

Hi --

We have some code that returns an object of a different class, depending
on some parameters. For example:

if param x is 1 and y is 1, we make an object of class C_1_1.
if param x is 1 and y is 2, we make an object of class C_1_2.

C_1_1 and C_1_2 share a common C ancestor, and in practice may be
identical, but theoretically, could have the same function name with two
different implementations underneath.

We have a file where all the C_X_Y classes are defined. It looks sort
of like this:

class C_1_1(C):
"""Creates a x=1 and y=1 class"""
def __init__(self):
C.__init__(self, 1, 1)

class C_1_2(C):
"""Creates a x=1 and y=2 class"""
def __init__(self):
C.__init__(self, 1, 2)

99% of the specific classes do the exact same thing. For a tiny few,
the class definition looks like this:

class C_3_5(C):
"""Creates a x=3, y=5 class."""
def __init__(self):
C.__init__(self, 3, 5)

def foo(self):
"""Redefine the default C.foo() function."""
return 99

The reason for this is that we want to allow different classes to do
non-standard behavior. In practice, however, it turns out that most of
the time, we don't need anything special.

Is this the best solution? Is there some way of doing a default vs.
non-default deal, without having to manually hardcode all the different
possible subclasses?

Thanks for the help.

--
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilson...asAndMakefiles
Nov 22 '05 #1
4 968
Would the approach of using a switch to decide to instatite which class
good for you, like:

py> class C:
py. name = 'C'
py.
py> class D:
py. name = 'D'
py.
py> switch = { (1, 1): C, (1,2): D }
py> x = 1
py> y = 2
py> c = switch[(x,y)]()
py> print c.name
D
py>

Nov 22 '05 #2
Rusty Shackleford wrote:
Hi --

We have some code that returns an object of a different class, depending
on some parameters. For example:

if param x is 1 and y is 1, we make an object of class C_1_1.
if param x is 1 and y is 2, we make an object of class C_1_2.

C_1_1 and C_1_2 share a common C ancestor, and in practice may be
identical, but theoretically, could have the same function name with two
different implementations underneath.

We have a file where all the C_X_Y classes are defined. It looks sort
of like this:
(snip)
99% of the specific classes do the exact same thing. For a tiny few,
the class definition looks like this:
(snip same code with minor differences...)
The reason for this is that we want to allow different classes to do
non-standard behavior. In practice, however, it turns out that most of
the time, we don't need anything special.

Is this the best solution?
No, of course - but I guess you knew it already !-)
Is there some way of doing a default vs.
non-default deal, without having to manually hardcode all the different
possible subclasses?


Here are the pieces of the puzzle:
- A dict is usually the best choice for lookups.
- A tuple can serve as key for a dict.
- A (reference to) a class object can be stored in a dict (or the name
of the class, as a string).
- the get() method of a dict allow for an optional default value to be
use if the requested key is not found

And here's a first go:

def get_object(x, y):
specials = {
(1, 2): C_1_2,
(33, 42): C_33_42,
}
# assume class C is the default class
klass = specials.get((x, y), C)
return klass()

Now if you store the class names as strings, ie :
specials = {
(1, 2): "C_1_2",
(33, 42): "C_33_42",
}

you can use a config file (ini, XML, Yaml, or even plain old python) to
store the 'specials' mapping and the default class name, and have
get_object() read from that config file. The trick is to get the class
from the class's name, which is solved with getattr():

def get_object(x, y):
specials = {
(1, 2): "C_1_2",
(33, 42): "C_33_42",
}
# assume class 'C' is the default class
class_name = specials.get((x, y), "C")

# from class name to class:
klass = getattr(module_where_classes_live, class_name)
return klass()
I think you should be able to solve your problem with this.

A last thing: the name of the module storing the classes can also be
stored in a conf file. Use __import__() to get the module object from
it's name.
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Nov 22 '05 #3
Rusty Shackleford wrote:
Hi --

We have some code that returns an object of a different class, depending
on some parameters. For example:

if param x is 1 and y is 1, we make an object of class C_1_1.
if param x is 1 and y is 2, we make an object of class C_1_2.

C_1_1 and C_1_2 share a common C ancestor, and in practice may be
identical, but theoretically, could have the same function name with two
different implementations underneath.

We have a file where all the C_X_Y classes are defined.
Is this the best solution? Is there some way of doing a default vs.
non-default deal, without having to manually hardcode all the different
possible subclasses?


How are you instantiating the correct class? You should be able to provide a default behaviour. For example if the classes are all defined in module C you could have a factory like this:

import C
def makeC(x, y):
subtype = 'C_%d_%d' % (x, y)
cls = getattr(C, subtype, C.C)
return cls(x, y)

Then in module C just define the subtypes you need to specialize; all other values of x and y will get the base class C.C.

Kent
Nov 22 '05 #4
Kent Johnson wrote:
Rusty Shackleford wrote:
...
C_1_1 and C_1_2 share a common C ancestor, and in practice may be
identical, but theoretically, could have the same function name with two
different implementations underneath.

...


How are you instantiating the correct class? You should be able to provide a default behaviour. For example if the classes are all defined in module C you could have a factory like this:

import C
def makeC(x, y):
subtype = 'C_%d_%d' % (x, y)
cls = getattr(C, subtype, C.C)
return cls(x, y)

Then in module C just define the subtypes you need to specialize; all other values of x and y will get the base class C.C.

Kent


Or, if you actually want different classes for each set of parameters (say for
debugging or introspection), you could compose the default ones on the fly:
import C
def makeC(x, y):
subtype = 'C_%d_%d' % (x, y)
cls = getattr(C, subtype, None)
if not cls:
# No specialized class found, so compose a default
# This requires C.C to be a new-style class
cls = type(subtype, (C.C,), {"__autogenerated__": True})
return cls(x, y)

Michael

Nov 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: WhiteRavenEye | last post by:
Why can't I subclass any window except mine in VB? Do I have to write dll for this? I've tried to subclass it with SetWindowLong but without success... Does anyone know how to subclass window...
4
by: GrelEns | last post by:
hello, i wonder if this possible to subclass a list or a tuple and add more attributes ? also does someone have a link to how well define is own iterable object ? what i was expecting was...
2
by: BJörn Lindqvist | last post by:
A problem I have occured recently is that I want to subclass builtin types. Especially subclassing list is very troublesome to me. But I can't find the right syntax to use. Take for example this...
6
by: Steven D'Aprano | last post by:
I've been working with the Borg design pattern from here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 and I'm having problems subclassing it. I'm a newbie, so I've probably...
11
by: Brent | last post by:
I'd like to subclass the built-in str type. For example: -- class MyString(str): def __init__(self, txt, data): super(MyString,self).__init__(txt) self.data = data
3
by: alotcode | last post by:
Hello: What is 'interprocess subclassing'? To give more context, I am writing in reference to the following remark: With the advent of the Microsoft Win32 API, interprocess subclassing was...
1
by: paul.hester | last post by:
Hi all, I'm planning to migrate a website from ASP to ASP .NET 2.0. The old page has a common include file that performs a series of tasks when every page loads. I'm new to ASP .NET 2.0 and am...
11
by: Peted | last post by:
Im using c# 2005 express edition Ive pretty much finished an winforms application and i need to significantly improve the visual appeal of the interface. Im totaly stuck on this and cant seem...
5
by: Ray | last post by:
Hi all, I am thinking of subclassing the standard string class so I can do something like: mystring str; .... str.toLower (); A quick search on this newsgroup has found messages by others
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.