Proper way to return an instance of a class from a class method ?

Chris Rebert clp2 at rebertia.com
Fri Mar 5 13:01:32 CET 2010


On Fri, Mar 5, 2010 at 2:35 AM, Auré Gourrier
<aurelien.gourrier at yahoo.fr> wrote:
<snip>
> QUESTION 2:
> If I go this way, I have a second problem: if I create a new class which
> inherits from the previous, I would expect/like the methods from the initial
> class to return instances from the new class:
>
> class MyClass2(MyClass):
>
>     def othermethods(self):
>         return MyClass2(whatever)
>
> Then I get:
>
> x = list1
> y = list2
> data = MyClass2([x,y])
> finaldata = data.transformdata()
>
> My problem is that finaldata is (of course) an instance of MyClass and not
> MyClass2. How do I deal with this ?

Get the object's actual class at runtime and use that.

#in MyClass
def transformdata(self):
    newdata = transform(data)
    return self.__class__(newdata)

When called on an instance of the subclass, self.__class__ will be
MyClass2 and everything will work out.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list