You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
defmulti_getattr(obj, attr, default=None):
""" Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is equivalent to x.a.b.c.d. When a default argument is given, it is returned when any attribute in the chain doesn't exist; without it, an exception is raised when a missing attribute is encountered. """attributes=attr.split(".")
foriinattributes:
try:
obj=getattr(obj, i)
exceptAttributeError:
ifdefault:
returndefaultelse:
raisereturnobjprintmulti_getattr(a, "hometown.name")
# New Yorkprintmulti_getattr(a, "hometown.name1", "abc")
# abc
# coding=utf-8from __future__ importunicode_literalsimportcollectionsimportoperator_default_stub=object()
defdeep_get(obj, path, default=_default_stub, separator='.'):
"""Gets arbitrarily nested attribute or item value. Args: obj: Object to search in. path (str, hashable, iterable of hashables): Arbitrarily nested path in obj hierarchy. default: Default value. When provided it is returned if the path doesn't exist. Otherwise the call raises a LookupError. separator: String to split path by. Returns: Value at path. Raises: LookupError: If object at path doesn't exist. Examples: >>> deep_get({'a': 1}, 'a') 1 >>> deep_get({'a': 1}, 'b') Traceback (most recent call last): ... LookupError: {u'a': 1} has no element at 'b' >>> deep_get(['a', 'b', 'c'], -1) u'c' >>> deep_get({'a': [{'b': [1, 2, 3]}, 'some string']}, 'a.0.b') [1, 2, 3] >>> class A(object): ... def __init__(self): ... self.x = self ... self.y = {'a': 10} ... >>> deep_get(A(), 'x.x.x.x.x.x.y.a') 10 >>> deep_get({'a.b': {'c': 1}}, 'a.b.c') Traceback (most recent call last): ... LookupError: {u'a.b': {u'c': 1}} has no element at 'a' >>> deep_get({'a.b': {'Привет': 1}}, ['a.b', 'Привет']) 1 >>> deep_get({'a.b': {'Привет': 1}}, 'a.b/Привет', separator='/') 1 """ifisinstance(path, basestring):
attributes=path.split(separator)
elifisinstance(path, collections.Iterable):
attributes=pathelse:
attributes= [path]
LOOKUPS= [getattr, operator.getitem, lambdaobj, i: obj[int(i)]]
try:
foriinattributes:
forlookupinLOOKUPS:
try:
obj=lookup(obj, i)
breakexcept (TypeError, AttributeError, IndexError, KeyError,
UnicodeEncodeError, ValueError):
passelse:
msg="{obj} has no element at '{i}'".format(obj=obj, i=i)
raiseLookupError(msg.encode('utf8'))
exceptException:
if_default_stub!=default:
returndefaultraisereturnobj
The text was updated successfully, but these errors were encountered:
python json 序列化及反序列化
namedtuple
object_hook
使用
namedtuple
反序列化为 namedtuple
序列化为 json
输出
封装:
总结:
序列化及反序列化都比较方便,但是
namedtuple
不能进行复制,不能修改使用
object_hook
反序列化为对象
获取对象属性
getattr
try
get
获取对象的嵌套属性
The text was updated successfully, but these errors were encountered: