2012-07-29 50 views
3

我對這個特殊問題有點困惑,現在我已經有這個麻煩了。問題是,我不知道如何正確添加一個新的類變量到已經定義的類。在我的場景中,我使用tweepy模塊並使用Streaming API來獲取包含'lol'的twitter消息。將類變量添加到定義的類

這是迄今爲止代碼:

import tweepy 

class StreamListener(tweepy.StreamListener): 
    #I want to add some code here in order to open a file 

    def on_status(self, status): 
     try: 
      #Rather than printing here I would like to write to the file 
      print status.text 
     except: 
      self.textOut.close() 

    auth1 = tweepy.auth.OAuthHandler(XXXXX, XXXX) 
    auth1.set_access_token(XXXXX, XXXXX) 
    api = tweepy.API(auth1) 

    textOut = open('twitterMessages.txt') 
    l = StreamListener() 
    streamer = tweepy.Stream(auth=auth1, listener=l, timeout=3000000000) 
    setTerms = ['lol', 'Lol', 'LOL'] 
    streamer.filter(None,setTerms) 

看我的意見。我想打開一個文件開始並寫入文件。問題是當我創建一個init方法時,它似乎覆蓋原始的init方法。

回答

3

使用super調用原__init__,和包裹文件I/O在with聲明:

auth1 = tweepy.auth.OAuthHandler('CONSUMER KEY','CONSUMER SECRET') 
auth1.set_access_token('ACCESS TOKEN','ACCESS TOKEN SECRET') 
api = tweepy.API(auth1) 

class StreamListener(tweepy.StreamListener): 
    def __init__(self, f): 
     super(StreamListener, self).__init__() 
     self._f = f 
    def on_status(self, status): 
     printf(status) 
     self._f.write(status.text) 

with open('twitterMessages.txt', 'w') as outf: 
    l = StreamListener(outf) 
    streamer = tweepy.Stream(auth=auth1, listener=l, timeout=3000000000) 
    setTerms = ['lol', 'Lol', 'LOL'] 
    streamer.filter(None,setTerms) 
3

您可以編寫自己的__init__仍調用基類__init__

class SubClass(BaseClass): 
    def __init__(self): 
     BaseClass.__init__(self) 
     # do whatever you want here 

如果您的自定義__init__你可以打開一個文件,然後執行,例如,self.outFile = open("somefile.txt", "w"),然後在on_status方法做self.outFile.write(status.text),和等等。