Is there a way to access __dict__ (or something like it) that includes base classes?

前端 未结 5 847
南旧
南旧 2020-12-20 12:42

Suppose we have the following class hierarchy:

class ClassA:

    @property
    def foo(self): return \"hello\"

class ClassB(ClassA):

    @property
    def         


        
5条回答
  •  粉色の甜心
    2020-12-20 13:03

    Sadly there isn't a single composite object. Every attribute access for a (normal) python object first checks obj.__dict__, then the attributes of all it's base classes; while there are some internal caches and optimizations, there isn't a single object you can access.

    That said, one thing that could improve your code is to use cls.__mro__ instead of cls.__bases__... instead of the class's immediate parents, cls.__mro__ contains ALL the ancestors of the class, in the exact order Python would search, with all common ancestors occuring only once. That would also allow your type-searching method to be non-recursive. Loosely...

    def get_attrs(obj):
        attrs = set(obj.__dict__)
        for cls in obj.__class__.__mro__:
            attrs.update(cls.__dict__)
        return sorted(attrs)
    

    ... does a fair approximation of the default dir(obj) implementation.

提交回复
热议问题