How would you determine where each property and method of a Python class is defined?

前端 未结 3 403
旧巷少年郎
旧巷少年郎 2021-01-14 11:41

Given an instance of some class in Python, it would be useful to be able to determine which line of source code defined each method and property (e.g. to implement

3条回答
  •  情深已故
    2021-01-14 12:00

    You are looking for the undocumented function inspect.classify_class_attrs(cls). Pass it a class and it will return a list of tuples ('name', 'kind' e.g. 'method' or 'data', defining class, property). If you need information on absolutely everything in a specific instance you'll have to do additional work.

    Example:

    >>> import inspect
    >>> import pprint
    >>> import calendar
    >>> 
    >>> hc = calendar.HTMLCalendar()
    >>> hc.__class__.pathos = None
    >>> calendar.Calendar.phobos = None
    >>> pprint.pprint(inspect.classify_class_attrs(hc.__class__))
    [...
     ('__doc__',
      'data',
      ,
      '\n    This calendar returns complete HTML pages.\n    '),
     ...
     ('__new__',
      'data',
      ,
      ),
     ...
     ('cssclasses',
      'data',
      ,
      ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']),
     ('firstweekday',
      'property',
      ,
      ),
     ('formatday',
      'method',
      ,
      ),
     ...
     ('pathos', 'data', , None),
     ('phobos', 'data', , None),
     ...
     ]
    

提交回复
热议问题