SoFunction
Updated on 2025-03-01

Detailed explanation of how to obtain member variables and temporary variables of a class in Python

Using Python reflection mechanism, statically obtain parameters from code blocks:

co_argcount: The total number of normal parameters, excluding parameters and * parameters.

co_names: Tuples of all parameter names (including parameters and * parameters) and local variable names.

co_varnames: Tuples of all local variable names.

co_filename: The file name where the source code resides.

co_flags: This is a numeric value, and each binary bit contains specific information. The more concerned are 0b100 (0x4) and 0b1000 (0x8). If co_flags & 0b100 != 0, it means that the *args parameter is used; if co_flags & 0b1000 != 0, it means that the **kwargs parameter is used. In addition, if co_flags & 0b100000(0x20) != 0, this means that this is a generator function.

 class A:
  def __init__(self, a, b, c):
    = a
    = b
    = c
   xx = 1
  def __str__(self):
   co = self.__init__.func_code
   co_names, co_varnames = 'co_names: ', 'co_varnames: '
   co_names += ','.join(co.co_names)
   co_varnames += ','.join(co.co_varnames)
   return ''.join((co_names, '\n', co_varnames))
 if '__main__' == __name__:
  obj = A(1, 2, 3)
  print str(obj)

result:

co_names: x,y,z
co_varnames: self,a,b,c,xx

The above detailed explanation of the method of obtaining member variables and temporary variables of Python classes is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.