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

前端 未结 3 390
旧巷少年郎
旧巷少年郎 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 11:58

    You are looking for the inspect module, specifically inspect.getsourcefile() and inspect.getsourcelines(). For example

    a.py:

    class Hello(object):
        def say(self):
           print 1
    
    >>> from a import Hello
    >>> hi = Hello()
    >>> inspect.getsourcefile(hi.say)
    a.py
    >>> inspect.getsourcelines(A, foo)
    (['   def say(self):\n        print 1\n'], 2)
    

    Given the dynamic nature of Python, doing this for more complicated situations may simply not be possible...

提交回复
热议问题