首页 > 其他 > 详细

元编程学习(1)

时间:2018-03-11 23:36:02      阅读:233      评论:0      收藏:0      [点我收藏+]
#!/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)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!