0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

twitterライブラリの仕組み

Last updated at Posted at 2014-02-05

リストメンバーの取得

# https://dev.twitter.com/docs/api/1.1/get/lists/members
# tはtwitterオブジェクト
t.lists.members

twitterライブラリを使用するときに、APIの/をtwitterオブジェクト.~.~ とつなげることで使えるのはどんな仕組みなんだぜ?と思い、ソースをみたら勉強になったのでメモ

class CallSample(object):

    def __init__(self,words=()):
        self.words = words

    def __getattr__(self, k):
        try:
            return object.__getattr__(self, k)

        except AttributeError:
            def extend_call(arg):
                return CallSample(words=self.words + (arg,))
            return extend_call(k)

    def __call__(self, **kwargs):
        words = []
        for word in self.words:
            #引数のディクショナリで既存のwordを書き換える。(無ければ既存値)
            words.append(str(kwargs.pop(word, word)))
        return '! '.join(words) + '!!!'

内部の処理を簡単にしたのが上記ソース

__getattr__で存在しない属性値なら、新しいオブジェクトを生成し返却、その際呼び出された文字列をストック。
__call__はクラスが関数として使用?されたら呼び出される
__call__が呼ばれたら、ストックした文字列を加工する(ここでは!で区切る)

twitterライブラリでは/で区切りURLを作成してるんですな。

今回作ったサンプルをを下記のように使用すると・・・・

hoge = CallSample()
print(hoge.れに.かなこ.ももか.しおり.あーりん.いくぜ.ももいろクローバー())

れに! かなこ! ももか! しおり! あーりん! いくぜ! ももいろクローバー!!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?