<div>A lot of my code supplement/replace the constructor with class factory methods.</div>
<div> </div>
<div>So, instead of:</div>
<div>>  a= A(...)</div>
<div> </div>
<div>I would write:</div>
<div>> a = A.from_file(...)</div>
<div>> a = A.create(...)</div>
<div>etc.</div>
<div> </div>
<div>This is implemented as follows:</div>
<div> </div>
<div>class A:</div>
<div>   def __init__(self, ...): pass</div>
<div> </div>
<div>   @classmethod</div>
<div>   def from_file(cls, ....):</div>
<div>        inst = cls()</div>
<div>        ....</div>
<div>        return inst</div>
<div> </div>
<div>Derived classes of A can of course use these factories to create instances of the derived class as well.</div>
<div> </div>
<div>The problem arise when the derived class needs a different implementation of the factory.</div>
<div>If it was a constructor (or any method for that matter), this would be achieved as:</div>
<div> </div>
<div>class B(A):</div>
<div>   def __init__(self, ...):</div>
<div>       A.__init__(self, ...)</div>
<div>      ....</div>
<div> </div>
<div>However, this can not be done with the factory:</div>
<div> </div>
<div>class B(A):</div>
<div>    @classmethod</div>
<div>    def from_file(cls, ...)</div>
<div>        inst = A.from_file(...)</div>
<div>        ....</div>
<div>        return inst</div>
<div> </div>
<div>will result with the type of the created object being A and not B.</div>
<div> </div>
<div>This can be overcome in two ways. The first (neat hack) is due to a colleague of mine, using static methods and default arguments:</div>
<div> </div>
<div>class A:</div>
<div>   @staticmethod </div>
<div>   def from_file(cls=None, ...)</div>
<div>       if not cls: cls = A</div>
<div>       inst = cls()</div>
<div>       ...</div>
<div> </div>
<div>class B(A):</div>
<div>
<div>   @staticmethod </div>
<div>   def from_file(cls=None, ...)</div>
<div>       if not cls: cls = B</div>
<div>       inst = A.from_file(cls, ...)</div>
<div>    </div>
<div> </div>
<div>The second is by delegating the work of the factory to an instance method:</div>
<div> </div>
<div>class A:</div>
<div>   @classmethod</div>
<div>   def from_file(cls,...)</div>
<div>       inst = cls()</div>
<div>       inst._from_file(...)</div>
<div>       return inst</div>
<div> </div>
<div>and then overriding the instance method and never touching the factory method.</div>
<div> </div>
<div> </div>
<div>Now, my questions are as follow:</div>
<div> </div>
<div>1/ Am I missing a third, more "standard" way of achieving inheritance of class methods?</div>
<div>2/ If not, I think future python's should have a syntax for this -- the first method I proposed is a neat hack, and the second is a workaround, but I wouldn't want the first method to be the official way of doing things, and I suspect there are some use cases that can not be implemented as nicely with the second method.
</div>
<div> </div>
<div> </div>
<div>Yoav</div></div>