Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, most of the time you think you need something like this, you don't; it's a sign that you're trying to treat Python like Java, and the solution is to step back and ask why you need a factory.</p> <p>Often, the simplest thing to do is to just have a constructor with defaulted/optional/keyword arguments. Even cases that you'd never write that way in Java—even cases where overloaded constructors would feel wrong in C++ or ObjC—may look perfectly natural in Python. For example, <code>size = Size(bytes=20)</code>, or <code>size = Size(20, Size.BYTES)</code> look reasonable. For that matter, a <code>Bytes(20)</code> class that inherits from <code>Size</code> and adds absolutely nothing but an <code>__init__</code> overload looks reasonable. And these are trivial to define:</p> <pre><code>def __init__(self, *, bits=None, bytes=None, kilobits=None, kilobytes=None): </code></pre> <p>Or:</p> <pre><code>BITS, BYTES, KILOBITS, KILOBYTES = 1, 8, 1024, 8192 # or object(), object(), object(), object() def __init__(self, count, unit=Size.BITS): </code></pre> <p>But, sometimes you <em>do</em> need factory functions. So, what do you do then? Well, there are two kinds of things that are often lumped together into "factories".</p> <p>A <code>@classmethod</code> is the idiomatic way to do an "alternate constructor"—there are examples all over the stdlib—<code>itertools.chain.from_iterable</code>, <code>datetime.datetime.fromordinal</code>, etc.</p> <p>A function is the idiomatic way to do an "I don't care what the actual class is" factory. Look at, e.g., the built-in <code>open</code> function. Do you know what it returns in 3.3? Do you care? Nope. That's why it's a function, not <code>io.TextIOWrapper.open</code> or whatever.</p> <p>Your given example seems like a perfectly legitimate use case, and fits pretty clearly into the "alternate constructor" bin (if it doesn't fit into the "constructor with extra arguments" bin).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload