1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Rep Power

    list of functions

    This may seem like an odd requirement, but I would like to declare a class with one of its methods definable at instantiation. So that for instance I might have the following

    class Func:
        numargs = 0
        rettype = None
        function = None
        def __init__(self, numargs, rettype, function):
            self.numargs = numargs
            self.rettype = rettype
            self.function = function
    cos = Func(1,'float', 'return math.cos(arg1)')
    sin = Func(1,'float', 'return math.sin(arg1)')
    print cos.function(0)   # this should output 1
    Does anyone know any way to make something like this work? The reason I need the class to be like this is that I want to maintain a list of functions along with certain characteristics and be able to call each one. I would also like to be able to dynamically add to the list. I could hardcode all the functions into the program and hardcode a list of the functions with parameters but that does not allow me to add functions on the fly. Any pointers would be greatly appreciated
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Hull, UK
    Rep Power
    I've tried to stay as close to your example as possible in this example but usually you would use __setattr__ method for this kind of thing; this lets you do things like f.x = value

    >>> class Foo: 
    ...     def __init__(self, *args):   
    ...         for each in args:
    ...             setattr(self, each.func_name, each)
    >>> def foo(x):
    ...     return x
    >>> def bar():
    ...     print 'Bar!!!'
    >>> f = Foo(foo, bar)
    >>> f.foo(True)
    >>> f.bar()
    Sorted . As you can see, you can now add functions to your class instance when you initiate it.

    You can find a simple example of using __setattr__ in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207

    Hope this helps,

    programming language development: www.netytan.com Hula

IMN logo majestic logo threadwatch logo seochat tools logo