Python: Class Methods Make Good Factories
Alex Martelli explained something to me a while back. One of the best uses of class methods is as constructors. For instance, if you want to have multiple constructors, but don't want to rely on one method that simply accepts different sorts of arguments, then use different class methods. The datetime module does this; it has class methods like fromordinal and fromtimestamp to create new datetime instances.
My first thought was that you could just as well use standalone factory functions. However, he brought up a good point. If I use a factory function, the class name is hard coded in the factory function. It can't easily return an instance of some subclass of the class. That's not the case with class methods.
Let me show you what I mean:class MyClass:
def __init__(self):
# This is the "base" constructor.
pass
@classmethod
def one_constructor(klass, foo):
# This is one special constructor.
self = klass()
self.foo =…
My first thought was that you could just as well use standalone factory functions. However, he brought up a good point. If I use a factory function, the class name is hard coded in the factory function. It can't easily return an instance of some subclass of the class. That's not the case with class methods.
Let me show you what I mean:class MyClass:
def __init__(self):
# This is the "base" constructor.
pass
@classmethod
def one_constructor(klass, foo):
# This is one special constructor.
self = klass()
self.foo =…