[Tutor] "classmethods"

Kent Johnson kent37 at tds.net
Sat May 21 12:29:20 CEST 2005


Kent Johnson wrote:
> Try this:
> 
> 	def fromFile(path):
> 		adict = {}
> 		alist = []
> 		#...
> 		#some part to read a file and to process data
> 		return MyClass(parameter1,parameter2,...,d)
>          fromFile = staticmethod(fromFile)
> 
> then client code will look like this:
> aClass = MyClass.fromFile('a/file/path')

A few more notes:

- There is no need to make fromFile a staticmethod of MyClass, it could also be a module level 
function. Writing it as a staticmethod puts it in the namespace of MyClass which may be handy.

- If you intend to subclass MyClass, the subclass constructors have compatible signatures and you 
want to be able to create subclasses with the same factory, a classmethod might work better.

  >>> class A(object):
  ...   def __init__(self, val):
  ...     self.val = val
  ...   def show(self):
  ...     print 'A.val:', self.val
  ...   def factory(cls, val):
  ...     return cls(val)
  ...   factory = classmethod(factory)
  ...
  >>> a=A.factory(3) # calls A.factory(A, 3)
  >>> a.show()
A.val: 3
  >>>
  >>> class B(A):
  ...   def show(self):
  ...     print 'B.val:', self.val
  ...
  >>> b=B.factory(22) # calls A.factory(B, 22)
  >>> b.show()
B.val: 22

- Finally, if you are using Python 2.4, you may prefer the decorator syntax for defining 
classmethods and staticmethods:
class A(object):
   ...
   @classmethod
   def factory(cls, val):
     return cls(val)

Kent



More information about the Tutor mailing list