class method vs static method

Michele Simionato michele.simionato at gmail.com
Tue Nov 21 04:14:18 EST 2006


Chris Brat wrote:
> Hi,
>
> I've done some reading up but I cant get my head around how/why class
> methods can be used as apposed to static methods.
>
> Can anyone give an example of where they have used class methods?
>
> Thanks,
> Chris

Class methods are typically used as factories:

class MyClass(object):
   @classmethod
   def myfactory(cls):
      self = cls()
      initialize(self)
      return self

With different factories you can obtain instances of the same classes
initialized in different ways. This is probably better than writing a
lot of subclasses
with different __init__s. This is my typical use case, but I am sure
others will post
many other examples of application. 

         Michele Simionato




More information about the Python-list mailing list