[Tutor] Class vs. Static Methods

Kent Johnson kent37 at tds.net
Wed Jun 22 01:03:08 CEST 2005


Chuck Allison wrote:
> 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.

No, a classmethod is passed the class that it is called on. If you have an inheritance tree you don't know this with a staticmethod.

 >>> class Test(object):
 ...   @staticmethod
 ...   def static(): # no args
 ...     print 'I have no clue how I was called'
 ...   @classmethod
 ...   def cls(cls):
 ...     print 'I was called on class', cls
 ...
 >>> t=Test()
 >>> t.static()
I have no clue how I was called
 >>> t.cls()
I was called on class <class '__main__.Test'>
 >>>
 >>> class T2(Test):
 ...   pass
 ...
 >>> t2=T2()
 >>> t2.static()
I have no clue how I was called
 >>> t2.cls()
I was called on class <class '__main__.T2'>
 >>> T2.cls()
I was called on class <class '__main__.T2'>

I can't think of a good use case for this at the moment...maybe some factory functions might care...

Kent



More information about the Tutor mailing list