Get The List Of A Class's Variables & Methods In Python
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 Foo(Bar): var1 = 3.14159265 va
Solution 1:
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.
Solution 2:
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__
Solution 3:
A third answer is the inspect module which does the same as above
Solution 4:
def getVariablesClass(inst):
var = []
cls = inst.__class__
for v in cls.__dict__:
if not callable(getattr(cls, v)):
var.append(v)
returnvar
if you want exclude inline variables check names on the __ at the start and the end of variable
Solution 5:
If you want to introspect your own classes, you can do it on class definition and cache it by the way:
classBar:
parent_prop = 0classFoo(Bar):
my_prop1 = 1
my_prop2 = 2defmethod1(self):
pass
SYMBOLS = [k for k inlocals().keys() ifnot k.startswith('_')]
if __name__ == '__main__':
print(Foo.SYMBOLS)
Output:
['my_prop1', 'my_prop2', 'method1']
Post a Comment for "Get The List Of A Class's Variables & Methods In Python"