Difference between static method and a function as a class attribute?

Gonçalo Rodrigues op73418 at mail.telepac.pt
Fri Sep 6 13:18:39 EDT 2002


On 06 Sep 2002 16:20:45 +0200, loewis at informatik.hu-berlin.de (Martin v.
Löwis) wrote:

>Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:
>
>> What are the differences, if any, between 1 and 2?
>
>In 1, test.funtest will be an unbound method; in 2, it will be a
>function.

Haaaa (a light goes on in an otherwise dark and empty skull) so the
function is implicitely mutated into an unbound method! Wasn't aware of
this, thought that Python did nothing at all and that is why I asked -
Always learning new things.

>
>> And if there are any differences do they really matter, that is, does
>> anybody has any test cases where 1 and 2 are not interchangeable?
>
>Sure:
>
>def m():
>    print "called ::m"
>class t1(object):
>    method = m
>
>class t2(object):
>    def m():
>        print "called t2::m"
>
>    method = staticmethod(m)
>
>t2.method()
>t1.method()
>
>gives
>
>called t2::m
>Traceback (most recent call last):
>  File "a.py", line 13, in ?
>    t1.method()
>TypeError: unbound method m() must be called with t1 instance as first argument (got nothing instead)
>
>Regards,
>Martin

Thanks and all the best,
Gonçalo Rodrigues




More information about the Python-list mailing list