以下语句中,QBDownloaderDayPrice 继承自 QBDownloader,执行时报错AttributeError: 'QBDownloaderDayPrice' object has no attribute '_QBDownloader__flag_encoding'。请教如何解决?
import time
import datetime
import tushare as ts
import pandas as pd
class QBDownloader(object):
def __init__(self):
self.__filename = ''
self.__df_data = null
self.__flag_encoding = 1
def saveto_csv(self):
if self.__flag_encoding == 1:
self.__df_data.to_csv(self.__filename, encoding='GBK')
else:
self.__df_data.to_csv(self.__filename)
class QBDownloaderDayPrice(QBDownloader):
def __init__(self):
self.__filename = 'QBdata\\DayPrice\\dp' + time.strftime("%Y%m%d", time.localtime()) + '.csv'
self.__df_data = self.get_df_data()
self.__flag_encoding = 1
def get_df_data(self):
#获取当天所有股票日价格,返回dataframe
df_day_price = ts.get_today_all()
return df_day_price
if name == '__main__':
obj_dl = QBDownloaderDayPrice()
obj_dl.saveto_csv()
print u'存储成功'
仔细查看error message就可以发现问题的。
所有attributes的名字,如果前面是两个下划线开头的
_
,python解释器会它实际的名字变成_<Class Name>__<Attributes Name>。在
QBDownloader
类中,__flag_encoding
变成了_QBDownloader__flag_encoding
.在
QBDownloaderDayPrice
类中,__flag_encoding
变成了_QBDownloaderDayPrice__flag_encoding
,saveto_csv()
函数本身访问的_QBDownloader__flag_encoding
被_QBDownloaderDayPrice__flag_encoding
替换。所以就找不到_QBDownloader__flag_encoding
了