What is a classmethod for?

Kragen Sitaker kragen at pobox.com
Mon Jun 10 18:08:27 EDT 2002

Frank Tobin <ftobin at neverending.org> writes:
> On Sun, 2 Jun 2002, Dennis Peterson wrote:
> > That's nice, but I can't think of a use for it, given that we have
> > inheritance and isinstance(). Can anyone enlighten me?
> Personally, I like using classmethods as secondary constructors, generally
> gones that are able to construct 'from' something.
> e.g.:
> class HostPortAddress(tuple):
> 	def from_str(self, s):
> 		return self(s.split(':', 1))
> 	from_str = classmethod(from_str)

That's so you don't have to write this?

class HostPortAddress(tuple): pass
def HostPortAddress_from_str(s): 
    return HostPortAddress(s.split(':', 1))

Are there times when it's more compelling?

More information about the Python-list mailing list