鍍金池/ 問答/Python/ AttributeError:" object has no attr

AttributeError:" object has no attribute"報(bào)錯(cuò),請(qǐng)教如何解決?

以下語句中,QBDownloaderDayPrice 繼承自 QBDownloader,執(zhí)行時(shí)報(bào)錯(cuò)AttributeError: 'QBDownloaderDayPrice' object has no attribute '_QBDownloader__flag_encoding'。請(qǐng)教如何解決?

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):
    #獲取當(dāng)天所有股票日價(jià)格,返回dataframe
    df_day_price = ts.get_today_all()
    return df_day_price

if name == '__main__':

obj_dl = QBDownloaderDayPrice()
obj_dl.saveto_csv()
print u'存儲(chǔ)成功'
回答
編輯回答
神經(jīng)質(zhì)

仔細(xì)查看error message就可以發(fā)現(xiàn)問題的。

所有attributes的名字,如果前面是兩個(gè)下劃線開頭的_,python解釋器會(huì)它實(shí)際的名字變成_<Class Name>__<Attributes Name>。

QBDownloader類中,__flag_encoding變成了_QBDownloader__flag_encoding.

QBDownloaderDayPrice類中,__flag_encoding變成了_QBDownloaderDayPrice__flag_encoding,saveto_csv()函數(shù)本身訪問的_QBDownloader__flag_encoding_QBDownloaderDayPrice__flag_encoding替換。所以就找不到_QBDownloader__flag_encoding

2018年8月31日 11:02