类型错误:__init__() 至少需要 4 个非关键字参数(提供了 3 个)

1 投票
3 回答
3994 浏览
提问于 2025-04-16 22:37

请给我点建议 :)

当我使用这个脚本时:

class CustomStreamListener(tweepy.StreamListener):

    def on_status(self, status):

        # We'll simply print some values in a tab-delimited format
        # suitable for capturing to a flat file but you could opt 
        # store them elsewhere, retweet select statuses, etc.



        try:
            print "%s\t%s\t%s\t%s" % (status.text, 
                                      status.author.screen_name, 
                                      status.created_at, 
                                      status.source,)
        except Exception, e:
            print >> sys.stderr, 'Encountered Exception:', e
            pass

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

# Create a streaming API and set a timeout value of 60 seconds.

streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60)

# Optionally filter the statuses you want to track by providing a list
# of users to "follow".

print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),)

streaming_api.filter(follow=None, track=Q)

出现了这样的错误:

Traceback (most recent call last):
  File "C:/Python26/test.py", line 65, in <module>
    streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60)
TypeError: __init__() takes at least 4 non-keyword arguments (3 given)

那我该怎么办呢?

3 个回答

0

这个问题的主要原因是使用了旧版本的tweepy。我之前用的是tweepy 1.7.1,遇到了同样的错误,后来我把tweepy更新到了1.8,问题就解决了。我觉得那个得到4个赞的回答应该被选为最佳答案,以便更清楚地说明解决方法。

1

__init__ 是一个类的构造函数,这里指的是 Stream 类。这个错误的意思是你在调用构造函数的时候,给的参数数量不对。

4

你的例子似乎来自这里。你正在使用Tweepy,这是一个用来访问Twitter API的Python库。

在Github上,这里Stream()对象的定义(假设你使用的是最新版本的Tweepy,请再确认一下!),

def __init__(self, auth, listener, **options):
        self.auth = auth
        self.listener = listener
        self.running = False
        self.timeout = options.get("timeout", 300.0)
        self.retry_count = options.get("retry_count")
        self.retry_time = options.get("retry_time", 10.0)
        self.snooze_time = options.get("snooze_time",  5.0)
        self.buffer_size = options.get("buffer_size",  1500)
        if options.get("secure"):
            self.scheme = "https"
        else:
            self.scheme = "http"

        self.api = API()
        self.headers = options.get("headers") or {}
        self.parameters = None
        self.body = None

因为你似乎传入了合适数量的参数,所以看起来CustomStreamListener()没有被初始化,因此没有作为参数传递给Stream()类。你可以先初始化一个CustomStreamListener(),然后再将它作为参数传递给Stream()

撰写回答