[Tutor] Class vs. Static Methods

Alan G alan.gauld at freenet.co.uk
Wed Jun 22 09:35:15 CEST 2005


----- Original Message ----- 
From: "Kent Johnson" <kent37 at tds.net>
> 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.

Aha! Like the OP I was aware of the class/no class distinction
but couldn't see how this helped since a static method implicitly
knows hich class it is in.

But this example shows the big difference, the static method
knows its in T1 but is not aware of inheritance so will
always respond as a T1. The classmethod is aware of inheritance
and will respond as whatever class is being accessed.

So If I have a heirarchy of shapes and want a class method that
only operates on the shape class itself, not on all the
subclasses then I have to use staticmethod whereas if I want
the class method to act on shape and each of its sub classes
I must use a classmethod. The canonical example being counting
instances. staticmethod would only allow me to count shapes
but class method would allow me to count all the sub classes
separately. Mind you this would require reprogramming the
class method for each new shape which is probably a bad
idea - overriding would be a better approach IMHO...

Neat, I understand, I think... Thanks Kent.

Alan G.

>  >>> 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
>  ...
>  >>> 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'>




More information about the Tutor mailing list