How to use a class property to store function variables?

Chris Rebert clp2 at rebertia.com
Wed Apr 28 01:43:56 CEST 2010


On Tue, Apr 27, 2010 at 4:36 PM, GZ <zyzhu2000 at gmail.com> wrote:
> I want to store a reference to a function into a class property.
>
> So I am expecting that:
>
> class A:
>     fn = lambda x: x
>
> fn = A.fn
> fn(1)
>
> Traceback (most recent call last):
>  File "<string>", line 1, in <string>
> TypeError: unbound method <lambda>() must be called with A instance as
> first argument (got int instance instead)
>
>
> The problem is that A.fn is treated as a bounded method. I really want
> A.fn to be a variable that stores a reference to a function. Is there
> any way to achieve this?

Use the staticmethod() decorator:

class A(object):
    @staticmethod
    def fn(x):
        return x

#rest same as before

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list