@Channelchan
2017-11-27T10:47:25.000000Z
字数 2579
阅读 11878
使用class语句来创建一个新类,class之后为类的名称并以冒号结尾,如下实例:
class ClassName:
'类的帮助信息' #类文档字符串
class_suite #类体
period 变量是一个类变量,它的值将在这个类的所有实例之间共享。你可以在内部类或外部类使用 factor.period 访问。
第一种方法init()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。
self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。
import talib as ta
class factor:
period = 5
def __init__(self, data):
self.close = data.close
self.volume = data.volume
def volume_up(self, short_period=5, long_period=20):
return pd.Series((ta.MA(self.volume.values,5)/ta.MA(self.volume.values,20)),index=self.volume.index)
def price_slope(self):
return pd.Series((ta.LINEARREG_SLOPE(self.close.values,5)),index=self.close.index)
import pandas as pd
from fxdayu_data import DataAPI
data = DataAPI.candle('600036.XSHG','D',length=100)
input_data = factor(data)
print(input_data.volume_up().tail())
datetime
2017-11-20 15:00:00 1.297457
2017-11-21 15:00:00 1.307877
2017-11-22 15:00:00 1.327108
2017-11-23 15:00:00 1.365542
2017-11-24 15:00:00 1.230205
dtype: float64
print(input_data.price_slope().tail())
datetime
2017-11-20 15:00:00 0.652
2017-11-21 15:00:00 0.739
2017-11-22 15:00:00 0.658
2017-11-23 15:00:00 0.161
2017-11-24 15:00:00 -0.124
dtype: float64
面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。
继承完全可以理解成类之间的类型和子类型关系。
需要注意的地方:继承语法 class 派生类名(基类名)://... 基类名写在括号里,基本类是在类定义的时候,在元组之中指明的。
在python中继承中的一些特点:
1:在继承中基类的构造(init()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。
2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别在于类中调用普通函数时并不需要带上self参数
3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。
如果在继承元组中列了一个以上的类,那么它就被称作"多重继承" 。
派生类的声明,与他们的父类类似,继承的基类列表跟在类名之后,如下所示:
# class SubClassName (ParentClass1[, ParentClass2, ...]):
# 'Optional class documentation string'
# class_suite
class MA(object): # 定义父类
__name__ = 'MA'
period = 10
def __init__(self):
print("调用父类构造函数")
def sma(self, df):
print('调用父类方法')
return df.rolling(self.period).mean()
def set_period(self, new_period):
MA.period = new_period
def get_period(self):
print ("父类周期 :", MA.period)
class MA_pct_change(MA): # 定义子类
change_period = 2
def __init__(self):
print ("调用子类构造方法")
def calculate_ma_diff(self, candle_data):
short_ma = self.sma(candle_data)
factor_ma = short_ma.pct_change(self.change_period)
return(factor_ma)
Son = MA_pct_change()
调用子类构造方法
print(Son.sma(data.close).tail())
调用父类方法
datetime
2017-11-20 15:00:00 27.984
2017-11-21 15:00:00 28.317
2017-11-22 15:00:00 28.698
2017-11-23 15:00:00 28.991
2017-11-24 15:00:00 29.293
Name: close, dtype: float64
Son.set_period(20)
Son.get_period()
父类周期 : 20
print(Son.calculate_ma_diff(data.close).tail())
调用父类方法
datetime
2017-11-20 15:00:00 0.012212
2017-11-21 15:00:00 0.014222
2017-11-22 15:00:00 0.014245
2017-11-23 15:00:00 0.013625
2017-11-24 15:00:00 0.009745
Name: close, dtype: float64