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

检查python类属性

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

检查python类属性

下面是困难的方法。这是简单的方法。不知道为什么我早就没想到。

import inspectdef get_user_attributes(cls):    boring = dir(type('dummy', (object,), {}))    return [item for item in inspect.getmembers(cls) if item[0] not in boring]

这是一个开始

def get_user_attributes(cls):    boring = dir(type('dummy', (object,), {}))    attrs = {}    bases = reversed(inspect.getmro(cls))       for base in bases:        if hasattr(base, '__dict__'): attrs.update(base.__dict__)        elif hasattr(base, '__slots__'): if hasattr(base, base.__slots__[0]):      # We're dealing with a non-string sequence or one char string     for item in base.__slots__:         attrs[item] = getattr(base, item) else:      # We're dealing with a single identifier as a string     attrs[base.__slots__] = getattr(base, base.__slots__)    for key in boring:        del attrs['key']  # we can be sure it will be present so no need to guard this    return attrs

这应该相当健壮。本质上,它通过获取

object
要忽略的默认子类上的属性来工作。然后,它获取传递给它的类的mro并以相反的顺序遍历它,以便子类键可以覆盖超类键。它返回键值对的字典。如果您想要一个键列表,
inspect.getmembers
则使用in中的值元组,然后在Python
3中返回
attrs.items()
list(attrs.items())

如果您实际上并不想遍历mro,而只想直接在子类上定义属性,那么它会更容易:

def get_user_attributes(cls):    boring = dir(type('dummy', (object,), {}))    if hasattr(cls, '__dict__'):        attrs = cls.__dict__.copy()    elif hasattr(cls, '__slots__'):        if hasattr(base, base.__slots__[0]):  # We're dealing with a non-string sequence or one char string for item in base.__slots__:     attrs[item] = getattr(base, item) else:      # We're dealing with a single identifier as a string     attrs[base.__slots__] = getattr(base, base.__slots__)    for key in boring:        del attrs['key']  # we can be sure it will be present so no need to guard this    return attrs


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

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

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