How to use a class property to store function variables?

MRAB python at mrabarnett.plus.com
Tue Apr 27 22:09:25 EDT 2010


Terry Reedy wrote:
> On 4/27/2010 7:36 PM, GZ 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 3.1, though you will have the same issue when calling it and same 
> fix that Chris gave.
> 
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
 >>> class A:
	fn = lambda x: x

	
 >>> fn = A.fn
 >>> fn(1)
1



More information about the Python-list mailing list