3

I'm a little confused on this particular problem and I have had this trouble for quite sometime now. The problem is that I don't know how to properly add a new class variable to an already defined class. In my scenario, I am using the tweepy module and using its Streaming API in order to get twitter messages that contain 'lol' in them.

Here is the code so far:

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)

Look at the comments I made. I want to open a file to begin with and write to the file. The problem is when I create an init method, it seems to override the original init method.

2 Answers 2

4

Use super to call the original __init__, and wrap the file I/O in a with statement:

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)
Sign up to request clarification or add additional context in comments.

Comments

3

You can write your own __init__ and still call the base class __init__:

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

If your customized __init__ you can open a file and do, e.g., self.outFile = open("somefile.txt", "w"), then in your on_status method do self.outFile.write(status.text), and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.