1. 程式人生 > >【Python】【元編程】【一】動態屬性和特性

【Python】【元編程】【一】動態屬性和特性

class join write msg pen mut quest pin sys

#19.1 使用動態屬性轉換數據
"""
#栗子19-2 osconfeed.py:下載 osconfeed.json
from urllib.request import urlopen
import os
import warnings
import json
import sys

URL = ‘http://www.oreilly.com/pub/sc/osconfeed‘
JSON = ‘data/osconfeed.json‘

path = os.path.join(sys.path[0],JSON)
path = path.replace(‘\\‘,‘/‘)


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

with open(path,‘rb‘) as fp:

return json.load(fp)

feed = load()
print(sorted(feed[‘Schedule‘].keys())) #[‘conferences‘, ‘events‘, ‘speakers‘, ‘venues‘]
for key,value in sorted(feed[‘Schedule‘].items()):
print(‘{:3} {}‘.format(len(value),key))
‘‘‘
1 conferences
494 events
357 speakers
53 venues
‘‘‘
print(feed[‘Schedule‘][‘speakers‘][-1][‘name‘]) #Carina C. Zona
print(feed[‘Schedule‘][‘speakers‘][-1][‘serial‘]) #141590
print(feed[‘Schedule‘][‘events‘][40][‘name‘]) #There *Will* Be Bugs
print(feed[‘Schedule‘][‘events‘][40][‘speakers‘]) #[3471, 5199]
"""

#栗子19-5 通過“點兒”來調用屬性
from urllib.request import urlopen
import os
import warnings
import json
import sys

URL = ‘http://www.oreilly.com/pub/sc/osconfeed‘
JSON = ‘data/osconfeed.json‘

path = os.path.join(sys.path[0],JSON)
path = path.replace(‘\\‘,‘/‘)


JSON1 = ‘data/osconfeed1.json‘

path1 = os.path.join(sys.path[0],JSON1)
path1 = path1.replace(‘\\‘,‘/‘)

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

with open(path1,‘rb‘) as fp:

return json.load(fp)

from collections import abc
class FrozenJSON:
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


raw_feed = load()
feed = FrozenJSON(raw_feed)
print(len(feed.Schedule.speakers))
























































































































































































































































































































































































































































































































































































































【Python】【元編程】【一】動態屬性和特性