栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

嵌套子对象/链接属性上的getattr和setattr?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

嵌套子对象/链接属性上的getattr和setattr?

您可以使用

functools.reduce

import functoolsdef rsetattr(obj, attr, val):    pre, _, post = attr.rpartition('.')    return setattr(rgetattr(obj, pre) if pre else obj, post, val)# using wonder's beautiful simplification: https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects/31174427?noredirect=1#comment86638618_31174427def rgetattr(obj, attr, *args):    def _getattr(obj, attr):        return getattr(obj, attr, *args)    return functools.reduce(_getattr, [obj] + attr.split('.'))

rgetattr
并且
rsetattr
是插入式替代
getattr
setattr
,这也可以处理点
attr
串。


import functoolsclass Person(object):    def __init__(self):        self.pet = Pet()        self.residence = Residence()class Pet(object):    def __init__(self,name='Fido',species='Dog'):        self.name = name        self.species = speciesclass Residence(object):    def __init__(self,type='House',sqft=None):        self.type = type        self.sqft=sqftdef rsetattr(obj, attr, val):    pre, _, post = attr.rpartition('.')    return setattr(rgetattr(obj, pre) if pre else obj, post, val)def rgetattr(obj, attr, *args):    def _getattr(obj, attr):        return getattr(obj, attr, *args)    return functools.reduce(_getattr, [obj] + attr.split('.'))

if __name__=='__main__':    p = Person()    print(rgetattr(p, 'pet.favorite.color', 'calico'))    # 'calico'    try:        # Without a default argument, `rgetattr`, like `getattr`, raises        # AttributeError when the dotted attribute is missing        print(rgetattr(p, 'pet.favorite.color'))    except AttributeError as err:        print(err)        # 'Pet' object has no attribute 'favorite'    rsetattr(p, 'pet.name', 'Sparky')    rsetattr(p, 'residence.type', 'Apartment')    print(p.__dict__)    print(p.pet.name)    # Sparky    print(p.residence.type)    # Apartment


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647230.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号