wong2
wong2

Reputation: 35740

Python get direct attributes of a class

Say I have a class:

class Foo(Parent):

    a = 1
    b = 2

    def bar(self, x):
        pass

I want to list all its attributes, and I found inspect:

import inspect
inspect.getmembers(Foo)

but this gives all attributes of Foo, including those from Parent, but I only want a, b, bar

Upvotes: 1

Views: 137

Answers (2)

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6861

There is a way, but it's dirty and you would have to filter out things like __module__ or __doc__:

Foo.__dict__

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599630

But attributes defined on the parent are direct attributes of the child. That's how inheritance works, and is a fundamental principle. The object doesn't know or care where they were defined.

If you needed to work this out somehow, one approach might be to get the list of attributes of the parent, and subtract them from the list of the child's attributes. But you really shouldn't need this.

Upvotes: 2

Related Questions