【问题标题】:Call decorated class method upon __init__()在 __init__() 上调用装饰类方法
【发布时间】:2019-12-20 06:07:57
【问题描述】:

我试图在类初始化时返回一个数据帧(这是一个连接两个数据帧的函数的结果)。由于我不能直接在 init 上使用装饰器,我必须在单独的方法上调用装饰器并将其传递给 init。

不幸的是,当我实例化类时,没有返回所需的结果数据帧?

我已经尝试使用 functools 'wraps' 包装函数,但我仍然没有得到想要的结果,尽管没有抛出错误

from functools import wraps

# the decorator function 
def join_results(func):
  @wraps(func)
  def join_df_wrapper(*args, **kwargs):
    close_df.columns = map(str.lower, close_df.columns)
    close_df.set_index(pd.to_datetime(close_df.dates))
    model_preds_df.columns = map(str.lower, model_preds_df.columns) 
    model_preds_df.set_index(pd.to_datetime(model_preds_df.dates))
    return func(*args, **kwargs)

class BackTestModelPNL(object):
  """test decorator"""

  def __init__(self, close_df: pd.DataFrame, model_preds_df: pd.DataFrame):
    self.close_df = close_df
    self.model_preds_df = model_preds_df
    self._initial_df = self.return_init_df()

  @property
  def initial_df(self):
    return self._initial_df

  # call decorator
  @join_results
  def return_init_df(self, *args, **kwargs):
    return self

# test that the class inits and returns joined results dataframe
df = BackTestModel(close_df, model_preds_df)


类的调用没有错误,但实例化类时未返回所需的结果(连接的数据帧)

【问题讨论】:

  • “我试图在类初始化时返回一个数据框”你能澄清你的用例吗?类应该在初始化时提供实例。如果你想返回别的东西,为什么不使用常规函数呢?
  • 目的是加入单独的数据帧以执行一系列检查。该类旨在执行这些检查,但也预先以静默方式加入两个不同的框架。

标签: python pandas python-decorators


【解决方案1】:

__init__() 应该总是返回 None。

https://docs.python.org/3/reference/datamodel.html#object.init

因为 new() 和 init() 在构造对象时协同工作 (new() 来创建它,init() 来定制它),no non-None init() 可以返回值;这样做会导致 TypeError 在运行时引发。

您可以使用属性来做到这一点,这是一种更 Python 的方式。 return_init_df() 函数可以计算您的初始数据帧。

# Define class 
class BackTestModel(object):
  def __init__(self, close_df: pd.DataFrame, model_preds_df: pd.DataFrame):
    self.close_df = close_df
    self.model_preds_df = model_preds_df
    self._initial_df = self.return_init_df()

  @property
  def initial_df(self):
    return self._initial_df


# test that the class inits and returns joined results dataframe
df = BackTestModel(close_df, model_preds_df)
inital_df = df.initial_df

【讨论】:

  • 感谢您的帮助!您能否解释一下属性装饰器如何与 @join_results 装饰器集成?你的意思是 initial-df 方法是我定义 join_results 逻辑的地方吗?谢谢!
  • 逻辑可能在'return_init_df()'中,它可以返回或设置_inital_df。该属性就像访问 _inital_df 的吸气剂
  • 我已经调整了原始代码以实现您的解决方案,请问这是否是您作为实现的意思?不幸的是,我在初始化时仍然没有得到 df?非常感谢您的帮助,非常感谢
猜你喜欢
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 2020-02-05
相关资源
最近更新 更多