Python: is there a way to reflect a list of all class attributes

For a class like

class MyClass: text = "hello" number = 123 

Is there a way in python to check MyClass and determine that it has two attributes text and number . I cannot use something like inspect.getSource(object) because the class with which I get its attributes is generated using SWIG (therefore they are hidden in .so :)).

So, I'm really looking for something equivalent to Java [Class.getDeclardFields][1]

Any help would be appreciated, otherwise I would have to solve this problem using SWIG + JAVA instead of SWIG + Python.

+4
source share
3 answers

I usually use dir(MyClass) . It also works with instances of objects.

edit I must mention that this is a shorthand function that I use to find out if my objects are created correctly. You might want to take a closer look at the reflection APIs if you do this programmatically.

It may also not work with linked libraries.

+8
source

Please write the actual, executable code snippets; don't expect people to answer your question to fix your code first.

 class MyClass(object): text = "hello" number = 123 for a in dir(MyClass): print a 
0
source
 >>> import cmath >>> dir(cmath) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'isinf', 'isnan', 'log', 'log10', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> cmath.atan <built-in function atan> 

dir matters and

 open("/usr/lib/python2.6/lib-dynload/cmath.so", O_RDONLY) = 4 read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\ 0@ \17\0\0004\0\0\0"..., 512) = 512 fstat64(4, {st_mode=S_IFREG|0644, st_size=32176, ...}) = 0 mmap2(NULL, 43824, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 4, 0) = 0x268000 mmap2(0x26f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 4, 0x6) = 0x26f000 mmap2(0x271000, 6960, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x271000 close(4) 

dynamically loading

0
source

Source: https://habr.com/ru/post/1306541/


All Articles