Proper way to return an instance of a class from a class method ?
Auré Gourrier
aurelien.gourrier at yahoo.fr
Fri Mar 5 05:35:42 EST 2010
Dear all,
I have what will probably sound as stupid questions for experienced Python users... which I am not, hence my seeking for some help.
------------
QUESTION 1:
I've implemeted a class which defines a container with 2 lists of data (with some specific format).
Some of the methods simply transform these data and therefore return a new container of 2 lists.
I want to be able to use these results without having to re-instanciate them, so I return them as instances of the class:
class MyClass:
def __init__(self, data):
#various checks for the format and content of data (data = [x,y] where x and y are 2 lists of floats)
self.data = data
def transformdata(self):
newdata = transform(data)
return MyClass(newdata)
In this way I can do:
x = list1
y = list2
data = MyClass([x,y])
moddata = data.transformdata()
moddata2 = moddata.transformdata()
Is that the correct way to go (i.e. is this pythonic) ? What I want to avoid is:
moddata = data.transformdata()
moddata2 = MyClass(moddata).transformdata()
------------
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 ?
All help will be much appreciated...
Cheers,
Auré
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100305/f57855fc/attachment.html>
More information about the Python-list
mailing list