Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách lấy source code từ object Python

Sử dụng inspect.getsource() để lấy source code của function, class, method...

Ví dụ

import inspect

class Foo:
    def bar():
        print('Hello')

print(inspect.getsource(Foo))

Đầu ra

class Foo:
    def bar():
        print('Hello')

Các object hỗ trợ

  • module, class, method, function, traceback, frame, code object.

Lưu ý

  • Ném OSError (Python 3) / IOError (Python 2) nếu không lấy được source (ví dụ: built-in functions, compiled extensions, code từ string).
  • inspect.getsourcefile(obj): Lấy đường dẫn file.
  • inspect.getsourcelines(obj): Trả về (lines, starting_line_number).

Ví dụ với function

def my_func(x, y=10):
    """Docstring."""
    return x + y

print(inspect.getsource(my_func))
# def my_func(x, y=10):
#     """Docstring."""
#     return x + y