3

Is it possible to find out which, if any, variables are set in a class's __init__ method without instantiating the class and inspecting its __dict__?

For example, if you load a module called mod with some class called Class, you can get the properties and methods of the class without creating an instance of it, using vars(mod.Class). If you create an instance of Class, you can also find out which variables are set upon instantiation, by looking at mod.Class().__dict__ or using vars(mod.Class()).

I'm wondering if you can get the class variables without instantiation. I'm trying to inspect the variables of an arbitrary class/type. It doesn't appear that the inspect module provides such a function.

qsfzy
  • 554
  • 5
  • 17
  • 5
    What is the actual problem you are trying to solve with this? – jonrsharpe Nov 01 '16 at 13:38
  • 1
    Short of introspecting the code, no. This is because variables in `__init__` are not declared; they are simply *created* once the method runs. – chepner Nov 01 '16 at 13:38
  • Possible duplicate of [Getting attributes of a class](https://stackoverflow.com/questions/9058305/getting-attributes-of-a-class) – palvarez May 25 '19 at 17:51

2 Answers2

0

It is possible to do that using the type keyword in Python. There you have the example like this:

>>> class X:
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))
prosti
  • 42,291
  • 14
  • 186
  • 151
0

Check getattr. You can use it to get the value of an attribute from a class.

>>> class MyClass:
...     var = 1
...
>>> getattr(MyClass, "var")
1