Use __init__ constructor as factory method
<p>I have a function which takes a factory method as an argument. Invoking the factory method will create an object. Now I thought that I could directly specify the constructor of the desired object/class <code>Fruit.__init__</code> as the factory method. But that does not work, since the <code>self</code> argument does "not exist" then. So I have to introduce an additional method <code>fruit_factory</code> which builds the object:</p>

<pre><code>def fruit_factory(owner):
    return Fruit(owner)

class Fruit:
    def __init__(self, owner):
        print('Making a fruit for ' + owner)

def make_snack_for_jim(snack_factory):
    snack_factory('Jim')

make_snack_for_jim(fruit_factory) # Works, but needs additional function
make_snack_for_jim(Fruit.__init__) # Does not work (no 'self' argument)
</code></pre>

<p>Is there a way to directly specify the constructor instead of needing to create an additional method?</p>

<p>Just pass in the class itself:</p>

<pre><code>&gt;&gt;&gt; make_snack_for_jim(Fruit)
Making a fruit for Jim
</code></pre>

<p>This sets your <code>snack_factory</code> to <code>Fruit</code> inside of the <code>make_snack_for_jim</code>, which you then call with <code>snack_factory('Jim')</code></p>

python factory-pattern