Static method

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Feb 18 09:23:27 EST 2010


mk a écrit :
> Bruno Desthuilliers wrote:
> 
>>>>
>>>>
>>>> class Foo4(object):
>>>>     """ working solution 2 : use a lambda """
>>>>     @staticmethod
>>>>     def bar(baaz):
>>>>         print baaz
>>>>
>>>>     tagada = {'bar': lambda x : Foo4.bar(x)}
>>>>
>>>>     def test(self, baaz):
>>>>         self.tagada['bar'](baaz)
>>>
>>> Huh? How does this one work? After all, while in Foo4 body, the Foo4 
>>> does not exist yet? Does lambda defer evaluation to runtime (when 
>>> it's executed) or smth?
>>
>> or smth, yes !-)
>>
>> A lambda expression evals to an ordinary function - just like a def 
>> statement - so Foo4 is not resolved until Foo4.tagada['bar'] is 
>> actually called.
> 
> This works, but... Foo4.bar in tagada is a staticmethod. So what's 
> needed is Foo4.bar.__get__(x)  (not that I'm that smart, I just got 
> 'staticmethod is not callable' exception).

Huh ???

class Foo4(object):

     @staticmethod
     def bar(baaz):
         print baaz

     tagada = {'bar': lambda x : Foo4.bar(x)}

     def test(self, baaz):
         self.tagada['bar'](baaz)

 >>> f = Foo4()
 >>> f.test(42)
42
 >>> Foo4.bar(42)
42
 >>>

WorksForMe(tm).



> It appears I have to use __get__ anyway while referring to bar in Foo4 
> methods:
 >
> def testrefer(self, val):
>     self.bar.__get__(val)
>     Foo4.bar.__get__(val)
> 
> At least I have to do this in my own code:
> 
>     def testit(self, fname):
>         self.print_internal_date.__get__(fname + 'c')
>         PYFileInfo.print_internal_date.__get__(fname + 'c')
> 
> 
> Or else I get "TypeError: 'staticmethod' object is not callable".

I think you broke something somewhere. Assuming you're using Python 2.x 
(>= 2.3 IIRC), my above code works.



More information about the Python-list mailing list