Get a list of class variables and methods in Python

If I have the following class, what's the best way to get an accurate list of variables and methods, excluding those from the superclass?

class Foo(Bar):
  var1 = 3.14159265
  var2 = Baz()
  @property
  def var3(self):
      return 42
  def meth1(self, var):
      return var

I need a tuple ('var1','var2','var3','meth1')with minimal overhead. This is done in a Django environment, which apparently puts some of the instance class variables __dict__in a read - only variable ; a feat that I cannot find for replication.

Here, what do I see while playing with him, any suggestions that go beyond __*the dir () directory or manually enumerate them?

>>> a=Foo()
>>> a
<__main__.Foo instance at 0x7f48c1e835f0>
>>> dict(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: iteration over non-sequence
>>> dir(a)
['__doc__', '__module__', 'meth1', 'var1', 'var2', 'var3']
>>> a.__dict__
{}
+5
source share
4 answers

If the class and its superclasses are known, for example:

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

, , , -

bases = Foo.mro()

... .

+7

a - , __dict__ , __init__. , a.__class__.__dict__

+3

The third answer is to check the module , which does the same as above.

+3
source
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 to exclude inline variables, check the names on __ at the beginning and end of the variable

0
source

All Articles