Get List of all attributes which are not inherited

徘徊边缘 提交于 2020-01-03 19:33:26

问题


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.


回答1:


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:
    def f(self):
        # overriden
        pass

    def h(self):
        pass

import inspect

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

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

which prints:

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

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:
    if k.startswith('__'):
        continue
    if k not in a:  # HERE: no 'or v != b[k]'
        print('Added in b:', k, v)


来源:https://stackoverflow.com/questions/48280605/get-list-of-all-attributes-which-are-not-inherited

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!