Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

0 views
Skip to first unread message

Chris Rebert

unread,
Mar 5, 2010, 7:01:32 AM3/5/10
to Auré Gourrier, pytho...@python.org
On Fri, Mar 5, 2010 at 2:35 AM, Auré Gourrier
<aurelien...@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

0 new messages