紀念一下,第一份python代碼__python

來源:互聯網
上載者:User
工作需要,學了2天python
#! /bin/env python2# coding: utf-8'netnode_list序列化json模組'import jsonfrom topology import NetNodeOUTPUT_JSON_FILE = '../data/topology.json'class NetNodeListEncoder(json.JSONEncoder):    """拓撲列表序列化json類    """    def default(self, obj):        """轉化方法        """        if not isinstance(obj,WrapNetNodeListEncoder):            raise ValueError('NetNodeListEncoder::param type err!')        return self._recurse(obj.net_node_list)    def _recurse(self, list=[]):        """遞迴轉化        """        l = []        if list:            for net_node in list:                d = net_node.__dict__                if net_node.sub_net:                    d['sub_net'] = self._recurse(net_node.sub_net)                else:                    del(d['sub_net'])                l.append(d)        return lclass WrapNetNodeListEncoder(object):    """封裝jsonencoder    exp:        encoder = WrapNetNodeListEncoder(netnode_list)        encoder.encode() # 轉碼        encoder.write_json() # 寫json檔案    """    def __init__(self,list=[]):        self.net_node_list = list;        self.json_str = ''    def encode(self):        """調用NetNodeListEncoder的encode        """        self.json_str = NetNodeListEncoder().encode(self)        return self.json_str    def write_json(self):        """寫json檔案        """        if self.json_str.strip():            with  open(OUTPUT_JSON_FILE, 'wt',  encoding='utf-8') as fd:                fd.write(self.json_str)        else:            print("WrapNetNodeListEncoder::write_json json_str is empty!")

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.