Get the list of a class's variables & methods in Python

后端 未结 4 1832
后悔当初
后悔当初 2021-01-02 18:06

If I have the following class, what\'s the best way of getting the exact list of variables and methods, excluding those from the superclass?

class F         


        
相关标签:
4条回答
  • 2021-01-02 18:19
    def getVariablesClass(inst):
    var = []
    cls = inst.__class__
    for v in cls.__dict__:
        if not callable(getattr(cls, v)):
            var.append(v)
    
    return var
    

    if you want exclude inline variables check names on the __ at the start and the end of variable

    0 讨论(0)
  • 2021-01-02 18:24

    In your example, a is an instance, its __dict__ will include all variables set in its __init__ function. To get all class variables, use a.__class__.__dict__

    0 讨论(0)
  • 2021-01-02 18:36

    A third answer is the inspect module which does the same as above

    0 讨论(0)
  • 2021-01-02 18:38

    If the class and its superclasses are known, something like:

    tuple(set(dir(Foo)) - set(dir(Bar)))
    

    If you want it to be more generic, you can get a list of the base classes using something like

    bases = Foo.mro()
    

    ...and then use that list to subtract out attributes from all the base classes.

    0 讨论(0)
提交回复
热议问题