Note: similar question here, but I don't believe it's an exact duplicate given the specifications.
Below, I have two classes, one inheriting from the other. Please note these are just illustrative in nature.
In _Pandas.array()
, I want to simply wrap a pandas DataFrame around the NumPy array returned from _Numpy.array()
. I'm aware of what is wrong with my current code (_Pandas.array()
gets redefined, attempts to call itself, and undergoes infinite recursion), but not how to fix it without name mangling or quasi-private methods on the parent class.
import numpy as np
import pandas as pd
class _Numpy(object):
def __init__(self, x):
self.x = x
def array(self):
return np.array(self.x)
class _Pandas(_Numpy):
def __init__(self, x):
super(_Pandas, self).__init__(x)
def array(self):
return pd.DataFrame(self.array())
a = [[1, 2], [3, 4]]
_Pandas(a).array() # Intended result - pd.DataFrame(np.array(a))
# Infinite recursion as method shuffles back & forth
I'm aware that I could do something like
class _Numpy(object):
def __init__(self, x):
self.x = x
def _array(self): # Changed to leading underscore
return np.array(self.x)
class _Pandas(_Numpy):
def __init__(self, x):
super().__init__(x)
def array(self):
return pd.DataFrame(self._array())
But this seems very suboptimal. In reality, I'm using _Numpy
frequently--it's not just a generic parent class--and I'd prefer not to preface all its methods with a single underscore. How else can I go about this?