adding attributes to a function, from within the function

Hung Jung Lu hungjunglu at yahoo.com
Mon Nov 3 04:51:03 EST 2003


Shu-Hsien Sheu <sheu at bu.edu> wrote in message news:<mailman.290.1067620017.702.python-list at python.org>...
> I think you would need to use a class rather than function.
> 
>  >>> class fn(object):
>     def __init__(self):
>         self.error = 'Error message'
> 
>         
>  >>> kk = fn()
>  >>> kk.error
> 'Error message'      

Yes, in Python it's more natural to use a class object for storing
attributes. What the original poster wanted was some sort of
"closure-like" function, that is, a function object that can carry
some data member as well. Also, in C++, you have static variables
inside functions. In Python, if you use a function object, you can't
insert attributes during the definition of the function.

In Python, an class instance can be made callable by implementing the
__call__() method. If the function is supposed to be singleton, then
you can use:

class fn(object):
    error = 'Error message'
    def __call__(self, x=None):
        if x is None:
            return 1
        else:
            return 2*x
fn = fn()      # gets rid of the class, this makes fn singleton
print fn()     # prints 1
print fn(3)    # prints 3
print fn.error # prints 'Error message'

regards,

Hung Jung




More information about the Python-list mailing list