Odd behavior with staticmethods

Scott David Daniels scott.daniels at acm.org
Sat Jul 1 17:15:55 EDT 2006


cmdrrickhunter at yaho.com wrote:
> I'm getting rather inconsistent behavior with staticmethod.
Not really.

>>>> class A:
> 	def orig():
> 		print "hi"
> 	st = staticmethod(orig)
> 	st2 = st
> 	wrapped = [ orig ]
> 	wrapped2 = [ st ]
...
 >>>> A.wrapped[0]() # ODD - wrapping orig() in a list makes orig() work?
 > hi
 >>>> A.wrapped2[0]() # ODD - copying st works -- A.st2() -- but copying 
it to a list fails?
...

When you put orig in wrapped, it is _before_ the class is built,
so you are placing a simple function of no args in a list.

When you put st in wrapped2, it is also _before_ the class is built,
so you are placing staticmethod(a simple function of no args) in a list.

You really should be using new-style classes, some things just
work wrong in "classic classes" (this is not one of those things,
however).

When the class gets built, the staticmethod wrapper is used to determine
how to build A.  The class construction gets handed the "namespace"
that was defined in the class suite, and it fumbles over the defined
names determining what conversions to apply (and looking for things
like "__metaclass__" and "__slots__").  For more on all of this read
the language reference, esp. the "Data Model" section, and probably that
on the difference between old-style and new-style classes.



--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list