[Tutor] Class vs. Static Methods

Chinook chinook.nr at tds.net
Wed Jun 22 00:56:29 CEST 2005


On Tue, 21 Jun 2005 17:58:09 -0400, Chuck Allison wrote
(in article <628909047.20050621155809 at freshsources.com>):

> Hello Chinook,
> 
> So is the main motivation for class methods so that you can have the
> class object available? It seems you can have that anyway in a static
> method by just asking. I'm sure there's a good reason for this, but I
> haven't yet gotten to the point of mastery where I can see a need for
> class methods (even after reading Martelli's Nutshell). I understand
> the syntax issues - I just don't see the need yet.
> 
> Tuesday, June 21, 2005, 3:28:48 PM, you wrote:
> 
> C> On Tue, 21 Jun 2005 16:52:09 -0400, Chuck Allison wrote
> C> (in article <10110159435.20050621145209 at freshsources.com>):
> 
>>> Sorry for the elementary question: I was wondering if someone could
>>> explain the difference to me between class and static methods. Coming
>>> from other languages, I'm used to static methods, but not "class
>>> methods". Thanks.
>>> 
>>> 
> 
> C> Does this help (from the QR)?
> 
> C> Static methods : Use staticmethod(f) to make method f(x) static (unbound).
> C> Class methods: like a static but takes the Class as 1st argument => Use f 

> = 
> C> classmethod(f) to make method f(theClass, x) a class method.
> 
> C> The decorators @staticmethod and @classmethod replace more elegantly the 
> C> equivalent declarations f = staticmethod(f) and f = classmethod(f).
> 
> C> Lee C
> 
> 
> C> _______________________________________________
> C> Tutor maillist  -  Tutor at python.org
> C> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 

Chuck,

Being fairly new to Python myself, I know how to create them and how to 
reference them.  I also know to use a static method in a factory pattern 
because it's name is then local to the scope it is defined in and it is 
called without an instance argument.  Mostly they work like simple functions 
that happen to be coded inside a class.  Static methods are usually used with 
class attributes to manage information that spans all instances generated 
from a class (a book's example is keeping track of the number of instances 
generated from a class).  Class methods are similar, but Python automatically 
passes the class (not an instance) into the method's leftmost argument.  

I have also read that such was introduced to clear up a gotcha before Python 
2.3

Yea, yea, your saying, but you never answered my question :~)  All I can 
relate to at this point in my learning cycle is that it's all a name space 
issue (re: instance, static and class).  Maybe one of the gurus can enlighten 
both of us further.  

Lee C




More information about the Tutor mailing list