Method call using __getattr__

background

I'm using https://pypi.python.org/pypi/twitter as the Twitter API library, but note that the method call has changed.

About Twitter Library

This library is not in the form of passing the URL of the API directly, but in the style of calling the method corresponding to the API. For example, for the API users / show, use the method twitter.users.show (). By the way, the URL of users / show is https://api.twitter.com/1.1/users/show.json?screen_name=twitterdev It looks like this.

However, this method is not implemented in the Twitter class and TwitterCall class of this library, and the URL is assembled from the method name using __getattr__ to call the API.

Sample code

As a code example, it looks like this

class A(object):
    def __init__(self, cls, urlparts):
        self.callable_cls = cls
        self.urlparts = urlparts 

    def __getattr__(self, k):
        print('called {}'.format(k))
        try:
            return object.__getattr__(self, k)
        except AttributeError:
            def extend_call(args):
                return self.callable_cls(self.callable_cls, self.urlparts + (args,))
            return  extend_call(k)

    def __call__(self, **kwargs):
        return self.urlparts

a = A(A, ())
res = a.users.show()
print(res)

Doing this will return tuples ('users','show') as a result. From now on, I will make a URL https://api.twitter.com/1.1/users/show.json?screen_name=twitterdev and call it.

As an explanation, when ʻa.users is called, there is no field or method called ʻusers, so __getattr__ is called. In it, ʻextend_call (users)is called and added as a tuple toself.urlparts. Then, a.users.show is called, because there is no method called show, getattris called. This also goes intoself.urlpartsas a tuple. When it is finally called as a method,call is called and returns the contents of self.urlparts`.

Summary

I don't think I'll use this implementation method myself, but as a note

Recommended Posts

Method call using __getattr__
Data visualization method using matplotlib (1)
Linear regression method using Numpy
Data visualization method using matplotlib (2)
SQL connection method using pyodbc
Data visualization method using matplotlib (+ pandas) (5)
Noise removal method using wavelet transform
Data visualization method using matplotlib (+ pandas) (4)
Watershed method in 3D images using ImageJ
Saddle point search using the gradient method