获取未继承的所有属性的列表 [英] Get List of all attributes which are not inherited

查看:38
本文介绍了获取未继承的所有属性的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个父类和一个子类,我想要列出所有在子类中定义但不从父类继承的属性.

If I have a parent class and a child class, I want list of all the attributes which are defined in child class but not inherited from parent class.

注意:我知道我可以从父类中获取所有属性的列表,并从子类中获取所有属性并进行交集,但这在我的情况下不起作用.

Note: I know I can get the list of all the attributes from parent class and get all the attributes from child class and take intersection, but this does not work in my scenario.

推荐答案

您可以使用以下事实:属性的地址与继承的地址不同(等于).参见示例:

You can use the fact, that the address of the attribute is not the same (equal) to the one inherited. See example:

from __future__ import print_function

class A:
    def f(self):
        pass

    def g(self):
        pass


class B(A):
    def f(self):
        # overriden
        pass

    def h(self):
        pass

import inspect

a = dict(inspect.getmembers(A))
# print(a)
b = dict(inspect.getmembers(B))
# print(b)

for k, v in b.items():
    if k.startswith('__'):
        continue
    if k not in a or v != a[k]:
        print('Not inherited:', k, v)

打印:

Not inherited: f <function B.f at 0x000002523A3E00D0>
Not inherited: h <function B.h at 0x000002523A3E0158>

如果不使用inspect模块,则可以使用简单的dir()代替.

If not using the inspect module, a simple dir(), may work instead.

您需要的不是十字路口,而是固定的差异. 并过滤掉魔术"元素.属性.

What you need is not an intersection, but a set difference. And filter out the "magic" attributes first.

编辑,您可能还想获取全新"的属性,即它们从来都不在基类中.您不必担心被覆盖的内容也是新的".您想去崭新的".

EDIT You may also want to get attributes, which are 'completely new', i.e. they were never in the base class. You don't care that the overriden stuff is also 'new'. You want to go for 'brand new'.

这只需要对上面的代码进行少量修改:

This requires only a small modification to the code above:

for k, v in b.items():
    if k.startswith('__'):
        continue
    if k not in a:  # HERE: no 'or v != a[k]'
        print('Added in b:', k, v)

这篇关于获取未继承的所有属性的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆