selecting base class from user input

danielx danielwong at berkeley.edu
Sun Aug 13 22:49:41 EDT 2006


Is your declaration of ABC supposed to have some_super as one of the
base classes? Your constructor has some_super as a parameter. What is
this supposed to mean in light of the declaration for ABC?

If you are trying to customize the base class of ABC by passing an
argument to the constructor of ABC, you should probably reconsider. If
constructing one instance of ABC can change ABC (the class) itself,
then the behavior of other instances will be affected as well. No
programmer can stay sane if he creates instances of a class that could
suddenly change its behavior (due to someone else's code).

What you could do instead is to create a function which constructs
classes based on the arguments it recieves. Then, you'll be able to
create instances of the generated classes (all this meta-thinking is
huring my brain ;). I am talking about something like this:

def createClass(name, base):
  exec "class %s(%s): pass" % (name, base)
  return eval( "name" )

...

Can you please tell us why you are doing this? My curiosity is killing
me!

Another meta-thought: Hopefully I've beaten everyone else to the punch
about that question. Is it just me, or will a reply with such a
question always tell the original poster that what he wants to do MUST
be flawed? I hope I have been gentler than this.

Jackson wrote:
> I want a class that will determine its base class by the argument passed
> in.  What I am about to write _does_not_work_, but it shows what I am
> trying to do.
>
> class ABC(some_super):
> 	def __init__(self,some_super):
>             some_super.__init__(self)
>
>             if some_super == list:
>                self.append('ABC')
>
>             elif some_super == dict:
>                self['ABC'] = None
>
>
> Then, the user can call this function:
>
> >>> example = ABC(list)
> >>> print example
> ['ABC']
>
> >>> example = ABC(dict)
> >>> print example
> {'ABC': None}
>
> Clearly, this is a bad example, but the central idea is what I am trying
> to do.  ABC is a particular example which can be represented in various
> forms.  I want an ABC class that will create the example in the form
> specified by the user.
> 
> So how can I achieve this? Thanks.




More information about the Python-list mailing list