In the parent, in place of UnlabelledDataset(data)
, use self.__class__(data)
. This should produce the correct answer in both classes.
As a minimalist example:
class A(object):
def __init__(self, data=None):
self.data = data
def f(self, data):
return self.__class__(data)
class B(A):
pass
When tested on the ipython command line:
In [15]: a = A()
In [16]: a.f('aaa')
Out[16]: <__main__.A at 0x2e99610>
In [17]: b = B()
In [18]: b.f('bbb')
Out[18]: <__main__.B at 0x2e99790>
Thus, as desired, method f
produces a new instance of A
when from a
and a new instance of B
when called from b
.
Example with each class having different constructor signatures
If class A
and B
have different constructors, then we can create a new method, make_new
, that handles the difference:
class A(object):
def __init__(self, data, x):
self.data = data
self.x = x
def make_new(self, myslice):
return self.__class__(self.data[myslice], self.x)
def f(self, myslice):
return self.make_new(myslice)
class B(A):
def __init__(self, data, x, y):
self.data = data
self.x = x
self.y = y
def make_new(self, myslice):
return self.__class__(self.data[myslice], self.x, self.y)