Can I define "static" (like in C++) methods in Python?
David LeBlanc
whisper at oz.net
Thu Apr 10 22:25:27 EDT 2003
> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Rene Pijlman
> Sent: Thursday, April 10, 2003 15:41
> To: python-list at python.org
> Subject: Re: Can I define "static" (like in C++) methods in Python?
>
>
> sdieselil:
> >Can I define methods which are attributes of class and not attributes of
> >instance?
> --
http://www.python.org/doc/FAQ.html#4.84
> René Pijlman
> --
I think René's link is out of date wrt current Python.
Starting with at least Python 2.2, you can:
class myclass:
myclassvar = 0 # standard class variable
def myclassmeth(myclass): # class as first arg
pass
myclassmeth = classmethod(myclassmeth)
def mystaticmeth(): # don't use self as first arg!
pass
mystaticmeth = staticmethod(mystaticmeth)
Then:
myclass.myclassmeth()
myclass.mystaticmeth()
are calls on the class, not an instance.
"As a brief explanation of these new kinds of methods, static methods aren't
passed the instance, and therefore resemble regular functions. Class methods
are passed the class of the object, but not the object itself."
(I'm not clear on the nuances from this...)
You can find additional info about this in the "What's New" section of the
Python doc included with the release IIRC. Also available at
http://www.python.org/doc/current/whatsnew/sect-rellinks.html
Personally, I think this is cumbersome: why not use classdef and staticdef
instead of def in the above to cause the needed class wrapping to occur?
Dave LeBlanc
Seattle, WA USA
More information about the Python-list
mailing list