码迷,mamicode.com
首页 > 其他好文 > 详细

元编程学习(1)

时间:2018-03-12 00:02:05      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:pre   def   tom   read   ppi   seq   data   self   request   

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from urllib.request import urlopen
import warnings
import os
import json
URL = http://bangth.com:8080/osconfeed.json
JSON = osconfeed.json

def load():
    if not os.path.exists(JSON):
        msg = downloading {} to {}.format(URL, JSON)
        warnings.warn(msg)
        with urlopen(URL) as remote, open(JSON, wb) as local:
            local.write(remote.read())
    with open(JSON) as fp:
        return json.load(fp)
    
feed = load()

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from collections import abc

class FrozenJSON:
    """一个只读接口,使用属性表示法访问JSON类对象
    """
    def __init__(self, mapping):
        self.__data = dict(mapping)
        
    def __getattr__(self, name):
        if hasattr(self.__data, name):
            return getattr(self.__data, name)
        else:
            return FrozenJSON.build(self.__data[name])
        
    @classmethod
    def build(cls, obj):
        if isinstance(obj, abc.Mapping):
            return cls(obj)
        elif isinstance(obj, abc.MutableSequence):
            return [cls.build(item) for item in obj]
        else:
            return obj

元编程学习(1)

标签:pre   def   tom   read   ppi   seq   data   self   request   

原文地址:https://www.cnblogs.com/luhouxiang/p/8546874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!