Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.python
Re: Proper way to return an instance of a class from a class method ?
Chris Rebert
3/5/2010 12:02:00 PM
On Fri, Mar 5, 2010 at 2:35 AM, Auré Gourrier
<aurelien.gourrier@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.re...
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: Proper way to return an instance of a class from a class method ?
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password