conditionally creating functions within a class?

Dan Bishop danb_83 at yahoo.com
Sat May 26 05:19:38 EDT 2007


On May 25, 7:44 pm, kaens <apatheticagnos... at gmail.com> wrote:
> 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()
> ...


class Test:
    def __init__(self, which):
        self.which = which
        if which == 'a':
            self.__class__ = TestB
        else:
            self.__class__ = TestC

class TestB(Test):
    def b(self):
        print "hello"

class TestC(Test):
    def c(self):
        print "goodbye"




More information about the Python-list mailing list