[Tutor] Counting objects: method vs. staticmethod vs. classmethod

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jun 22 05:32:49 EDT 2020


On 22/06/2020 03:35, boB Stepp wrote:
> What I want to do:  Every time I instantiate an object of a particular
> class I wish to generate a unique id dependent on a particular
> attribute value and the current number of objects created with that
> attribute value.  Playing around tonight I have come up with the same
> technique expressed slightly differently.  Which is best for what I
> want to do?  Is there a better way to do what I want to do?

They all can work, its mostly down to semantics.

global functions are notionally for working with objects of any
type.

class methods are for working with the instances of a particular
class,

static methods are, IMHO, a fudge that I never use!

So semantically, if you want to apply the function to multiple
classes - or all then make it a global function. (In fact you may
really want to look into tinkering with the metaclass mechanism!!)
You might also consider adding a call to the fuction from the __init__()
methods of the relevant classes.

But if its a single class, or a class hierarchy, then make it
a class method. (If its a few unrelated classes you could also
make it a class method of a mixin class which you then inherit
into all of the target classes.)

In practice it won't make much difference but in terms
of expressing intent it is probably bet to locate it where
the purpose suggests.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list