我对这个特殊问题有点困惑,而且我已经有这个麻烦了很长一段时间了.问题是我不知道如何正确地将新的类变量添加到已定义的类中.在我的场景中,我正在使用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方法.
最佳答案 使用
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)