是否可以调用 __init__ 中的方法来设置属性?

问题描述

我想编写一个包含计算衡量波动性(金融)类。计算计算实现每天使用日内高频数据的差异。然而,技术性不真正的问题。我的问题是更普遍的,关于OOP设计在Python更具体

我遇到的问题是,下面的作品的代码。但是从目前我添加/更改的东西,它不工作了。因此,我怀疑有我的课的设计中一些错误。我唯一能想到的就是你不能在 _init_ 中使用方法设置属性代码如下:

import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt

DAL = pd.read_pickle('../data/DAL_timeseries.pkl') # stock prices -> pd.Series with datetime index

class Volatility():

    ''' 
    Class that contains multiple calculations for realized variance/volatility:

        - Realized variance 

    '''

    def __init__(self,stock):
        self.stock = stock
        self.daily_prices = self.stock.resample("1D")
        self.bv = self.calculate_bv()

    def estimator_bv(self,one_day_prices):
        # used to calculate bipower variance 
        if (len(one_day_prices) > 0):
            returns = np.abs( np.diff(np.log(one_day_prices)) )
            return (np.pi / 2.0) * np.inner(returns[1:],returns[:-1])
        else: 
            return np.nan

    def calculate_bv(self):
        bv = self.daily_prices.apply(self.estimator_bv)
        return bv.rename("bv").dropna()

    def plot(self):
        plt.plot(self.bv)

vola = Volatility(DAL)
vola.plot()

---> returns nice plot 

上述工程的代码,但是奇怪的是,当我添加一些东西到plot()方法,e.g:

def plot(self):
  plt.plot(self.bv,label="bv")
  plt.legend()

我收到此错误

NameError                                 Traceback (most recent call last)
~/Desktop/case_fe/code/volatility.py in 
     46 
     47 
---> 48 vola = Volatility(DAL)

~/Desktop/case_fe/code/volatility.py in __init__(self,stock)
     20         self.stock = stock
     21         self.daily_prices = self.stock.resample("1D")
---> 22         self.bv = self.calculate_bv()
     23 
     24     def estimator_bv(self,one_day_prices):

~/Desktop/case_fe/code/volatility.py in calculate_bv(self)
     40 
     41     def calculate_bv(self):
---> 42         return bv.rename("bv").dropna()
     43     def plot(self):
     44 

NameError: name 'bv' is not defined`

当我删除plt.legend()行不知何故作品再次如预期?这个错误不会也认为,如果添加不同的变化或新的方法来我的班。这真的让我困惑,我觉得我失去了一些重要的东西。

PS:我是新来的Python写OOP,但试图用正确的术语

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...