向定义的类添加类变量

2024-09-29 03:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这个问题有点困惑,我已经有一段时间了。问题是我不知道如何正确地将新的类变量添加到已经定义的类中。在我的场景中,我使用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方法。在


Tags: toselfauthapiherestatusopenfile
2条回答

您可以编写自己的__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),依此类推。在

使用^{}调用原始的__init__,并在with语句中包装文件I/O:

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)

相关问题 更多 >