Python 中使用类修饰器修饰类方法如何处理 self?

2016-01-27 15:24:22 +08:00
 KIDJourney

这个是装饰器类。

class PostCache:
    def __init__(self, func):
        self.func = func
        self.redis = redis.StrictRedis()

    def __call__(self, url_list):
        url_not_cached = []
        for url in url_list:
            if self.redis.get(url):
                self.redis.expire(url, 600)
            else:
                url_not_cached.append(url)
                self.redis.set(url, '1')
                self.redis.expire(url, 600)

        return self.func(url_not_cached)

这个是要被装饰的方法。

@rediscache.PostCache
    def __get_content_list(self, url_list):
        content_list = []

        for url in url_list:
            content_list.append(self.get_content(url))

            time.sleep(config_intervaltime())

        return content_list

然后报错

File "crawler.py", line 28, in get_posts
    post_content_list = self.__get_content_list(url_list)
TypeError: __call__() missing 1 required positional argument: 'url_list'

该如何解决呢?

3630 次点击
所在节点    Python
9 条回复
kinghui
2016-01-27 15:25:50 +08:00
```python
@rediscache.PostCache()
def __get_content_list(self, url_list):
....
```
bobuick
2016-01-27 15:27:36 +08:00
你需要确保它实现了 __call__() 和 __get__() 方法
kinghui
2016-01-27 15:28:10 +08:00
看错了, 请忽略我
KIDJourney
2016-01-27 15:30:39 +08:00
@bobuick 为什么要实现__get__()呢?
[PythonDecoratorLibrary]( https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)
KIDJourney
2016-01-27 15:31:18 +08:00
@bobuick 看到了,多谢了。
KIDJourney
2016-01-27 15:35:15 +08:00
@bobuick 还是不太明白。。我再去看一下。
julyclyde
2016-01-27 20:51:39 +08:00
同问,为什么__get__()
关注
phithon
2016-01-27 22:46:37 +08:00
不知道楼主是不是这个意思
https://gist.github.com/phith0n/afe56234e3301435c3dd
KIDJourney
2016-01-28 00:29:04 +08:00
@phithon 多谢了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/253726

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX