Idiomatic Python for generating a new object from within a class
<p>I have a method on one of my objects that returns a new instance of that same class. I'm trying to figure out the most idiomatic way to write this method such that it generates a new object of the same type without duplicating code.</p>

<p>Since this method uses data from the instance, my first pass is:</p>

<pre><code>class Foo(object):
    def get_new(self):
        data = # Do interesting things
        return Foo(data)
</code></pre>

<p>However, if I subclass Foo and don't override get_new, calling get_new on SubFoo would return a Foo! So, I could write a classmethod:</p>

<pre><code>class Foo(object):

    @classmethod
    def get_new(cls, obj):
        data = # Munge about in objects internals
        return cls(data)
</code></pre>

<p>However, the data I'm accessing is specific to the object, so it seems to break encapsulation for this not to be a "normal" (undecorated) method. Additionally, you then have to call it like <code>SubFoo.get_new(sub_foo_inst)</code>, which seems redundant. I'd like the object to just "know" which type to return -- the same type as itself!</p>

<p>I suppose it's also possible to add a factory method to the class, and override the return type everywhere, without duplicating the logic, but that seems to put a lot of work on the subclasses.</p>

<p>So, my question is, what's the best way to write a method that gives flexibility in type of class without having to annotate the type all over the place?</p>
