Python元编程动态属性和特性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python元编程动态属性和特性相关的知识,希望对你有一定的参考价值。

#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元编程动态属性和特性的主要内容,如果未能解决你的问题,请参考以下文章

《Python高性能编程》——列表元组集合字典特性及创建过程

编程里面元组和数组的区别是啥?

python元编程之实现定制类--使用描述符,__slots__,__new__篇

Qt笔记——元对象系统

PythonCookbook第八章(元编程)

Python元编程描述符