staticmethod

Jeremy Yallop jeremy at jdyallop.freeserve.co.uk
Tue Feb 25 18:36:02 EST 2003


I find staticmethod()'s behaviour a bit surprising.  In particular:

Why does staticmethod() `work' on uncallable objects?

  >>> staticmethod('huh?')
  <staticmethod object at 0x8152eb8>

I'd expect this to raise an exception.

Why can't I make a class attribute into a staticmethod outside the
class definition?

  >>> class A:
  ...     def foo():
  ...             pass
  ...
  >>> A.foo = staticmethod(A.foo)
  >>> A.foo
  <unbound method A.foo>

The `problem' is just with methods;  staticmethod() does the right
thing (i.e., what I expect it to do) with functions when used outside
of a class definition:

  >>> class A:
  ...     pass
  ...
  >>> A.foo = lambda:x
  >>> A.foo
  <unbound method A.<lambda>>
  >>> A.foo = staticmethod(lambda:x)
  >>> A.foo
  <function <lambda> at 0x402c2144>

To be clear, I know the `proper' way to call staticmethod().  It's the
behaviour when it's used in a way that differs from the standard
example that's puzzling me.

Jeremy.




More information about the Python-list mailing list