[Tutor] instance method call issue

Alan Gauld alan.gauld at btinternet.com
Sun Oct 14 17:21:38 CEST 2012

On 14/10/12 13:34, Osemeka Osuagwu wrote:

> I understand instance, static and class methods but I'm still
> struggling with when and where they should be used.

You can pretty much ignore static methods, they were almost an
historic 'accident' superseded, in most cases, by class methods. The 
number of cases where a staticmethod is really needed is very low.

class methods you will rarely need but they are used when you want to do 
something to the entire class of objects. i.e. something that affects 
all instances both existing and future. Or they could be used where 
there are no instances (yet). Factory methods, instance selection
methods, modifying shared attributes, instance pooling, are all
examples. To give some kind of heuristic based on my personal usage, I 
use class methods in almost all my bigger projects. Such a project might 
have 20 or 30 (or more) classes. Out of that maybe 2 or 3 will have any 
class methods.

Instance methods are by far the most common. These are the things you 
want to do to a specific instance of the class. Changes to one instance 
have no effect on other instances of the same class.

> In the code below, I can't seem to get around calling an instance
> method (__reality_check()) from within a class method (update_grid()),

It's not a class method, you want to update a specific instance of a 
grid. update_grids() might be a class method if you wanted to, say,
change the maximum buffer size used to store the grids, or cause all 
grids to display the word 'empty' instead of a blank. Of course to do 
that you would need access to all the instances to update their existing 
values so the constructor would need to store a reference to itself in 
the class somewhere (or maybe in a separate shared database).
The class method would then iterate over all instances calling their 
instance method update_grid(). This is a common(*) class method pattern,
where a plural class method calls the singular instance methods
of all the instances.

(*) I say common, but of course class methods are not common
     so its a very relative term!


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list