constructor classmethods

Chris Angelico rosuav at gmail.com
Tue Nov 8 20:15:46 EST 2016


On Wed, Nov 9, 2016 at 10:01 AM,  <teppo.pera at gmail.com> wrote:
> One solution is:
>
> class Example:
>     def __init__(self, queue=None):
>         self._queue = queue or Queue()
>
> Fine approach, but technically __init__ has two execution branches and someone staring blindly coverages might require covering those too. Then we can use class method too.
>
> class Example:
>     def __init__(self, queue):
>         self._queue = queue
>
>     @classmethod
>     def create(cls):
>         q = Queue()
>         # populate_with_defaults
>         # Maybe get something from db too for queue...
>         return cls(q)
>
> As said, create-method is for convenience. it can (and should) contain minimum set of arguments needed from user (no need to be 15 even if __init__ would require it) to create the object.
>

You gain nothing, though. Whether your code paths are in create() or
in __init__, you still have them. You can make __init__ take no
mandatory arguments (other than self) and then it's still just as easy
to use. Tell me, without looking it up: How many arguments does the
built-in open() function take? But you don't have to worry about them,
most of the time.

Python has idioms available that C++ simply can't use, so what's right
for C++ might well not be right for Python, simply because there's
something better.

ChrisA



More information about the Python-list mailing list