[Baypiggies] Assigning functions as class variables

AM ams.fwd at gmail.com
Sat May 31 06:35:04 CEST 2014


On 05/30/2014 09:28 PM, Nanshu Chen wrote:
> Hmmm.. I’d like to call back my previous reply, as I still think 
> although the workaround works, it is not the right way of doing 
> things. The following code is better:
> -----------------
> def foo(a):
>     print a
>
> class X(object):
>
>     @classmethod
>     def bar(cls, fn):
>         cls.fn = staticmethod(fn)
>
>     @classmethod
>     def baz(cls, a):
>         cls.fn(a)
>
> X.bar(foo)
> X.baz(12)
> -------------------
>
> Nanshu
>
>
> On Friday, May 30, 2014 at 9:10 PM, Nanshu Chen wrote:
>
>> Do you think the following can be a possible workaround?
>>
>> def foo(a):
>>     print a
>>
>> class X(object):
>>     fn = [None]
>>
>>     @classmethod
>>     def bar(cls, fn):
>>         cls.fn[0] = fn
>>
>>     @classmethod
>>     def baz(cls, a):
>>         cls.fn[0](a)
>>
>> On Friday, May 30, 2014 at 8:51 PM, AM wrote:
>>
>>> Hi.
>>>
>>> What I am trying to do is assign a function to a class variable and use
>>> it. For e.g.:
>>>
>>>
>>> def foo(a):
>>> print a
>>>
>>> class X(object):
>>>
>>> @classmethod
>>> def bar(cls, fn):
>>> cls.fn = fn
>>>
>>> @classmethod
>>> def baz(cls, a):
>>> cls.fn(a)
>>>
>>>
>>> X.bar(foo)
>>> X.baz(12)
>>>
>>> If I run this I get:
>>> TypeError: unbound method foo() must be called with X instance as first
>>> argument (got int instance instead)
>>>
>>> I sort of understand why allowing this might cause a bit of trouble as
>>> fn could be an unbound method which receives X as the first argument,
>>> however I don't quite understand this particular error.
>>>
>>> Changing foo to accept another argument also does not work. If someone
>>> could enlighten me about:
>>>
>>> 1. Why exactly is calling the method disallowed in pretty much all 
>>> forms?
>>>
>>> 2. How do people work around this?
>>>
>>> that would be great.
>>>
>>> Thanks.
>>> AM
>>> _______________________________________________
>>> Baypiggies mailing list
>>> Baypiggies at python.org <mailto:Baypiggies at python.org>
>>> To change your subscription options or unsubscribe:
>>> https://mail.python.org/mailman/listinfo/baypiggies
>>
>
Thanks. That was it.

AM


More information about the Baypiggies mailing list