Doruk Doruk - 3 months ago 19
Python Question

Getting fields of derived class

In Python, I can get a classes fields with

__dict__
. Here I have two questions:

Is there a better way to get fields? Because it only brings fields that has values.
How can I get fields that exist only in class itself, not the base class?

Answer

Check this:

from types import FunctionType

class A (object):
    def test(self):
        pass

class B(A):
    def test12(self):
        pass


print([x for x,y in A.__dict__.items() if type(y) == FunctionType])

print([x for x,y in B.__dict__.items() if type(y) == FunctionType])

For attributes which are not methods, try this:

attributes = [x for x,y in B.__dict__.items() if (type(y) != FunctionType and type != callable)]

[a for a in attributes if not(a.startswith('__') and a.endswith('__'))]