Static method

mk mrkafk at gmail.com
Thu Feb 18 07:42:57 EST 2010


Bruno Desthuilliers wrote:
>> I think I know where the problem is: what resides in tagdata is a 
>> static method 'wrapper', not the function itself, according to:
> 
> Indeed. Sorry, I'm afraid I gave you bad advice wrt/ using a 
> staticmethod here - I should know better :( (well, OTHO staticmethods 
> are not something I use that often).

Do not worry the least bit! I'm testdriving on a closed circuit here for 
sake of becoming better 'driver', I'm not going to drive like this on 
the streets.

> class Foo2(object):
>     """ naive solution : kinda work, BUT will fail
>         with the real code that has  plain functions
>         in 'tagada'
>     """
>     @staticmethod
>     def bar(baaz):
>         print baaz
> 
>     tagada = {'bar': bar}
> 
>     def test(self, baaz):
>         self.tagada['bar'].__get__(self)(baaz)

Well I could always do:

if isinstance(self.tagada['bar'], staticmethod):
	self.tagada['bar'].__get__(self)(baaz)
else:
	self.tagada['bar'](baaz)

But 1. this apparently defeats the purpose of using print_internal_date 
on instance/class in 'normal' way, and 2. I probably shouldn't be doing 
that since using isinstance is apparently like playing with yourself: 
while technically legal, people look at you weirdly. :-)

> 
> class Foo3(object):
>     """ working solution 1 : defer the wrapping
>         of 'bar' as a staticmethod
>     """
>     def bar(baaz):
>         print baaz
> 
>     tagada = {'bar': bar}
> 
>     bar = staticmethod(bar)
> 
>     def test(self, baaz):
>         self.tagada['bar'](baaz)

Neat! I like this one.

> 
> 
> 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?

> 
> 
> """ and as a "less worse" solution """
> 
> def foo5bar(baaz):
>    print baaz
> 
> class Foo5(object):
>     tagada = {'bar': foo5bar}
> 
>     bar = staticmethod(foo5bar)
> 
>     def test(self, baaz):
>         self.tagada['bar'](baaz)
> 

Yes. I probably should have stayed with this one in the first place. I 
feel bad for using up bandwidth and people's attention with such stuff...





More information about the Python-list mailing list