[Tutor] Class vs. Static Methods

Kent Johnson kent37 at tds.net
Thu Jun 23 13:01:16 CEST 2005

Alan G wrote:
>>This is a neat trick. But can't this also be done with a static
> method
>>that accesses a static data attribute the same way?
> I don't think so because the static mehod can only see
> the attributes of Shape not of Line. 

Well, it can *see* Point._count and Line._count, it just doesn't know which one it should increment.

> It doesn't have
> access to the cls value in Kent's code below...
>>>> @classmethod
>>>> def count(cls):
>>>>   try:
>>>>     cls._count += 1
>>>>   except AttributeError:
>>>>     cls._count = 1
> So if it tried to incremet count every instance of every
> kind of shape would increment the shape counter - which may
> be what you want under some circumstances, but it wouldn't
> know which of the subclasses was calling it so couldn't
> access their counters.

Yes. In the absence of inheritance module methods, staticmethods and classmethods all have access to pretty much the same information. In the presence of inheritance, if you want to know the actual class a method was called on you need a classmethod.


More information about the Tutor mailing list