简体   繁体   中英

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

有一种方法,但是很脏,您必须过滤掉诸如__module____doc__类的东西:

Foo.__dict__

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM