检查python类属性

检查python类属性,第1张

检查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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5644595.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存