constructor classmethods

Ethan Furman ethan at stoneleaf.us
Wed Nov 2 10:40:12 EDT 2016


On 11/02/2016 06:46 AM, stestagg at gmail.com wrote:

> I was hoping to canvas opinion on using classmethods as constructors over __init__.
>
> We've got a colleague who is very keen that __init__ methods don't contain any logic/implementation at all, and if there is any, then it should be moved to a create() classmethod.

So every Python programmer who is used to creating new instances with `ThatThing()` will have to learn that some of your classes need to be `ThatThing.create()` ?

Horrible idea.

The purpose of classmethods that create the same kind of object is to provide constructors that take different things -- for example:

class date(object):

     def __init__(self, year, month, day):
         self.year = year
         self.month = month
         self.day = day

     @classmethod
     def from_stardate(cls, sd):
         ad = sd - SOME_CONSTANT_VALUE
         year = ...
         month = ...
         day = ...
         return cls(year, month, day)

If the goal is to make testing easier, one way to do that is:

def __init__(self, ..., queue=None):
     if queue is None:
         queue = Queue.Queue()
     self.queue = queue

--
~Ethan~



More information about the Python-list mailing list