conditionally creating functions within a class?

kaens apatheticagnostic at gmail.com
Fri May 25 20:44:44 EDT 2007


So, I have a class that has to retrieve some data from either xml or
an sql  database.
This isn't a problem, but I was thinking "hey, it would be cool if I
could just not define the functions for say xml if I'm using sql", so
I did some fiddling around with the interpreter.

First, I try conditionally creating a function, period:

a = 'a'

if(a == 'a')
    def b:
        print "hello"
else:
    def c:
        print "goodbye"

this works fine. b is defined, c is not. change the value of a and b
gets defined and not c (sorry for the one-letter variables here, but
for these little examples I don't think they detract much)

then I try doing this within a function:

class test:
    def __init__(self,which):
        self.which = which

    if(self.which == 'a'):
        def b:
            print "hello"
    else:
        def c:
            print "goodbye"

tester = test('a')
tester.b()

This doesn't "compile", says "Name 'self' is not defined". I assume
this is because of scope, something like it hasn't made the object
yet, so there is no self attribute. . . but I thought that python
wouldn't even bother reading that class statement until I tried to
make a test object, and that it would do the __init__ function before
anything else, so I'm a bit fuzzy here.

Next I try creating the functions through functions:

class test:
    def __init__(self, which):
        self.which = which
        self.chooser()

    def chooser(self):
        if( self.which == 'a'):
            def b(self):
                print "hello"
        else:
            def c(self):
                print "goodbye"

tester = test('a')
tester.b()

this tells me "instance has no attribute b.

I'm pretty sure this is all a scoping error of some sort (I could be
wrong), but I don't have my head wrapped around it at all. Anyone with
more knowledge care to explain what's going on?

Also, would there be a way to conditionally create functions in a
class? It doesn't really matter, but it'd be nice if I weren't
creating functions that I absolutely will not need for certain
instances at runtime



More information about the Python-list mailing list