将类变量添加到已定义的类

时间:2012-07-29 21:42:56

标签: python

我对这个特殊问题感到有些困惑,我现在已经遇到了这个麻烦。问题是我不知道如何正确地将新的类变量添加到已定义的类中。在我的场景中,我使用tweepy模块并使用其Streaming API来获取包含'lol'的推特消息。

目前为止是以下代码:

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 方法。

2 个答案:

答案 0 :(得分:4)

使用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)

答案 1 :(得分: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),依此类推。