Static method
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Thu Feb 18 08:00:03 EST 2010
mk a écrit :
> Bruno Desthuilliers wrote:
(snip)
>> 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. :-)
As far as I'm concerned, this would be a valid use case for isinstance.
But it breaks uniformity and requires quite a lot of mostly useless code.
>>
>> 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.
Not me - with the wrapping so far away from the definition, it's too
easy to miss part of the "process" when you come back to this code 6
month later.
>>
>>
>> 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.
>> """ 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...
Why so ? You learned something, I learned something, and quite a few
other people will now have a chance to learn something. Sensible use of
bandwith as far as I'm concerned. wrt/ people's attention, don't worry,
it's up to the reader to pay attention or skip the whole topic !-)
More information about the Python-list
mailing list