What's an example use case for a Python classmethod?
Helper methods for initialization:
class MyStream(object): @classmethod def from_file(cls, filepath, ignore_comments=False): with open(filepath, 'r') as fileobj: for obj in cls(fileobj, ignore_comments): yield obj @classmethod def from_socket(cls, socket, ignore_comments=False): raise NotImplemented # Placeholder until implemented def __init__(self, iterable, ignore_comments=False): ...
Well __new__
is a pretty important classmethod. It's where instances usually come from
so dict()
calls dict.__new__
of course, but there is another handy way to make dicts sometimes which is the classmethod dict.fromkeys()
eg.
>>> dict.fromkeys("12345"){'1': None, '3': None, '2': None, '5': None, '4': None}
I don't know, something like named constructor methods?
class UniqueIdentifier(object): value = 0 def __init__(self, name): self.name = name @classmethod def produce(cls): instance = cls(cls.value) cls.value += 1 return instanceclass FunkyUniqueIdentifier(UniqueIdentifier): @classmethod def produce(cls): instance = super(FunkyUniqueIdentifier, cls).produce() instance.name = "Funky %s" % instance.name return instance
Usage:
>>> x = UniqueIdentifier.produce()>>> y = FunkyUniqueIdentifier.produce()>>> x.name0>>> y.nameFunky 1