<blockquote>
<p>What is the best way to rewrite this so that, instead of calling <code>ProgressPrinter.create([file])</code>, users could directly call <code>ProgressPrinter([file])</code> with same result?</p>
</blockquote>
<p>只是克制一下。您真正想要的是用户对您的代码感到满意。当我看到<code>ProgressPrinter.create([file])</code>时,我可以假设一个工厂将创建与<code>ProgressPrinter</code>相关但可能属于不同类的对象。您希望它们是子类,这很好</p>
<p>但是,当我看到<code>ProgressPrinter([file])</code>时,我希望对象正好来自<em>类,而不是子类的成员。这意味着这段代码将更难阅读和理解,这是您肯定不想要的。我知道Python允许它,我甚至知道如何做到这一点。但这是不自然的,因为程序员不需要这样做</p>
<p>规则是遵循既定的模式。您可以按照@Barmar的建议使用委托给子对象(<strong>非</strong>子类),也可以坚持工厂模式。但请不要使用反模式</p>
<hr/>
<p>如果您真的想这样做,诀窍是在new中构建并配置一个适当子类的对象。但是必须使用<code>Object.__new__</code>来构建子类的对象。如果只使用标准创建,则会递归到<code>ProgressPrinter.__new__</code>,导致堆栈溢出</p>
<p>最小的改变是用这个<code>__new__</code>方法替换<code>__init__</code>方法:</p>
<pre><code>def __new__(cls, file):
if (cls == ProgressPrinter): # delegate sub object creation
return ProgressPrinter.create(file)
pp = super(ProgressPrinter, cls).__new__(cls) # trick to avoid recursion
pp.file = file
return pp
</code></pre>
<p>您还可以删除create方法并将其代码直接复制到<code>__new__</code></p>
<p>但这只是向您展示Python语言的可能性,我仍然强烈建议您不要在生产代码中使用它,并坚持使用更好的工厂模式。未来的维护人员肯定会责怪您使用这种反模式</p>