我对这个问题有点困惑,我已经有一段时间了。问题是我不知道如何正确地将新的类变量添加到已经定义的类中。在我的场景中,我使用tweepy模块并使用其流式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方法。在
您可以编写自己的
__init__
并仍然调用基类__init__
:如果自定义的
__init__
可以打开一个文件并执行操作,例如,self.outFile = open("somefile.txt", "w")
,那么在on_status
方法中执行self.outFile.write(status.text)
,依此类推。在使用^{} 调用原始的
__init__
,并在with
语句中包装文件I/O:相关问题 更多 >
编程相关推荐