对于如何直接从父类的__init__
函数继承变量,我有些困惑。例如,我有以下内容:
class BaselineModels:
def __init__(self):
self.logpath = './log/models/'
self.mpath = './models/'
然后,我创建一个具有自己的__init__
并调用super()
的子类,但是我似乎无法访问self.mpath
。我知道与self
绑定到类实例有关,但是由于我有很多子类不想复制这些路径变量,因此我将如何实现此功能。 / p>
我想要这样做的原因是,我从子类中调用了父类的函数,该子类使用父类的self
变量(csv_to_df
是父类的成员):
def csv_to_df(self) -> tuple:
"""Reads in CSV file declared in __init__ (self.rpath) and converts it to a number of Pandas DataFrames.
Returns:
tuple: Returns tuple of Pandas DataFrames; user features, item features and
interactions between items.
"""
df = pd.read_csv(self.rpath, sep='\t')
return df
从子类中调用它会导致
Traceback (most recent call last):
File "model_baselines.py", line 480, in <module>
als.run()
File "model_baselines.py", line 366, in run
df = self.csv_to_df()
File "model_baselines.py", line 46, in csv_to_df
df = pd.read_csv(self.rpath, sep='\t')
AttributeError: 'ALS' object has no attribute 'rpath'
子类定义
class ALS(BaselineModels):
def __init__(self):
super()
self.model_name = 'als'
def run(self):
df = self.csv_to_df()
我从文件底部调用als.run()
。
编辑:已更新为包含子类定义
答案 0 :(得分:3)
您必须调用__init__()
对象的super()
方法。像这样:
class BaselineModels:
def __init__(self):
self.logpath = './log/models/'
self.mpath = './models/'
class ALS(BaselineModels):
def __init__(self):
super().__init__()
self.model_name = 'als'
def run(self):
df = self.csv_to_df()
als = ALS()
als.mpath
# returns:
'./models/'
答案 1 :(得分:0)
您也可以遵循此方法。
class BaselineModels:
def __init__(self):
self.logpath = './log/models/'
self.mpath = './models/'
class ALS(BaselineModels):
def __init__(self):
super(ALS, self).__init__()
self.model_name = 'als'
def run(self):
df = self.csv_to_df()
als = ALS()
als.mpath
# returns:
'./models/'