我有一个内部有2个方法的类,我现在面临的问题是弄清楚如何将类中的方法调用到不同的模块中来执行我想要执行的任务。我可以轻松地将方法定义为静态,其中包含5个参数,但我不想这样做,因为我将在同一个类中添加越来越多的方法,并且我希望将此类继承到另一个
class IDList(object):
def __init__(self, dsnDate, dsnExpel, dsnEOD, dsnIDay, SnapShot):
self.dsnDate = dsnDate
self.dsnExpel = dsnExpel
self.dsnEOD = dsnEOD
self.dsnIDay = dsnIDay
self.SnapShot = SnapShot
def get_partIDlist(self):
prev_dt = self.dsnDate[self.dsnDate.bus_dt == prcs_dt]['prev_dt'].iloc[0]
prev_partID = self.dsnExpel[self.dsnExpel['prcs_dt'] == prev_dt][self.dsnExpel.corp_cd == 3][self.dsnExpel.rltnshp_cd == 'PRIME_BROKERED'][['map_id', 'part_id']]
part_id = self.dsnEOD[self.dsnEOD.bus_dt == prcs_dt][self.dsnEOD.run_cn == run_cn][self.dsnEOD.part_stat_cd == 'C'][self.dsnEOD.lvl_cd == 'A'][['map_id', 'part_id']]
IDaypart_id = pd.DataFrame(columns=['map_id', 'part_id', 'wndw_hr_nb'])
for snp in self.SnapShot:
part_id_IDay = self.dsnIDay[self.dsnIDay.bus_dt == prcs_dt][self.dsnIDay.run_cn == run_cn][self.dsnIDay.part_stat_cd == 'C'][self.dsnIDay.lvl_cd == 'A'][self.dsnIDay.wndw_hr_nb == snp][['map_id', 'part_id']]
part_id_IDay['wndw_hr_nb'] = snp
IDaypart_id = IDaypart_id.append(part_id_IDay)
part_idList = pd.concat([part_id, part_id_IDay])
return(part_idList)
现在,在不同的模块上,我尝试导入此类并调用方法来执行任务。我有几种方法可以进行不同的计算。这是我如何称呼这个
from pnl.exp.Engine import IDList
part_idList = IDList.get_partIDlist(var_bus_dt, part_rltnshp, cmpnt_chrg, iday_cmpnt_chrg, [8,11,12])
当我以这种方式调用此方法时出现错误,虽然我将一个值传递给参数python说'missing'。
Traceback (most recent call last):
File "<stdin>", line 1, in <module> TypeError: get_partIDlist() missing 1 required positional argument: 'SnapShot'
答案 0 :(得分:1)
嗯,有两种/三种方法可以解决这个问题:
快速而不那么聪明的方式(你可能不想调用IDList对象的成员函数)
from pnl.exp.Engine import IDList
idl = IDList(var_bus_dt, part_rltnshp, cmpnt_chrg, iday_cmpnt_chrg, [8,11,12])
part_idList = idl.get_partIDlist()
作为一种静态方法,您期望这种行为的方式:
class IDList(object):
@staticmethod
def get_partIDlist(dsnDate, dsnExpel, dsnEOD, dsnIDay, SnapShot):
prev_dt = dsnDate[dsnDate.bus_dt == prcs_dt]['prev_dt'].iloc[0]
prev_partID =dsnExpel[dsnExpel['prcs_dt'] == prev_dt][dsnExpel.corp_cd == 3][dsnExpel.rltnshp_cd == 'PRIME_BROKERED'][['map_id', 'part_id']]
part_id =dsnEOD[dsnEOD.bus_dt == prcs_dt][dsnEOD.run_cn == run_cn][dsnEOD.part_stat_cd == 'C'][dsnEOD.lvl_cd == 'A'][['map_id', 'part_id']]
IDaypart_id = pd.DataFrame(columns=['map_id', 'part_id', 'wndw_hr_nb'])
for snp in SnapShot:
part_id_IDay = dsnIDay[dsnIDay.bus_dt == prcs_dt][dsnIDay.run_cn == run_cn][dsnIDay.part_stat_cd == 'C'][dsnIDay.lvl_cd == 'A'][dsnIDay.wndw_hr_nb == snp][['map_id', 'part_id']]
part_id_IDay['wndw_hr_nb'] = snp
IDaypart_id = IDaypart_id.append(part_id_IDay)
part_idList = pd.concat([part_id, part_id_IDay])
return(part_idList)
from pnl.exp.Engine import IDList
part_idList = IDList.get_partIDlist(var_bus_dt, part_rltnshp, cmpnt_chrg, iday_cmpnt_chrg, [8,11,12])
IDList类甚至不执行任何操作,您只需将get_partIDlist()定义为pnl.exp.Engine中的模块范围函数,并将导入行更改为:
from pnl.exp.Engine import get_partIDlist