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

Martin v. Löwis loewis at informatik.hu-berlin.de
Fri Sep 6 16:20:45 CEST 2002


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.

> 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



More information about the Python-list mailing list