python 魔术函数调用的实现

场景

实现一个python调用java接口的功效,java接口是以http方法供给的。为了实现比拟舒畅的调用的方法,我不预备以send({"method": "echo"})这类方法调用,而是api.echo()

但是python里面并没有供给相似php__call__callStatic的函数

依据python的__getattr__来实现一个,但是这个解决计划不完善,有局限性。

实现

# encoding: utf-8

import json
import urllib, urllib2

class OPS(object):
    s = None

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

    def sendRequest(self, msg):
        postData = json.dumps(msg)
        print(postData)
        req = urllib2.Request(self.s, postData)
        try:
            resp = urllib2.urlopen(req)
        except Exception as e:
            return False
        cnt = resp.read()
        try:
            cnt = json.loads(cnt)
        except Exception as e:
            pass
        return cnt

    def __getattr__(self, name):
        def func(*args, **kwargs):
            # args 不处置 (由因而序列化成json传输的,python的dict是无序的,摈弃对list的处置)
            data = {
                "method": name,
                "parameter": kwargs
            }
            return self.sendRequest(data)
        return func

if __name__ == "__main__":
    ops = OPS("你的http接口调用地址")
    print(ops.hello(word="你好"))