2009-10-13 6 views
66

JavaScript에서는 함수 정의를 인쇄 할 수 있습니다. 파이썬에서 이것을 수행 할 수있는 방법이 있습니까?파이썬이 함수 정의를 인쇄 할 수 있습니까?

(그냥 대화 형 모드에서 놀고 open()없이 모듈을 읽고 싶었습니다.) 나는 호기심이 많았습니다. 그것은이 할 수있는 경우

+0

이 기능의 소스가 있습니다. 그게 뭐가 잘못 됐니? –

+0

대화식 모드에서 help (function)를 사용하여 함수에 대한 docstring을 표시 할 수 있습니다. – monkut

+0

이 질문의 사본이 있습니다 : http://stackoverflow.com/questions/427453/how-can-i-get-the-source-code-of-a-python-function –

답변

93

, 당신은 inspect.getsource 사용할 수 있습니다

>>> import re 
>>> import inspect 
>>> print inspect.getsource(re.compile) 
def compile(pattern, flags=0): 
    "Compile a regular expression pattern, returning a pattern object." 
    return _compile(pattern, flags) 

하지만, 분명히 전용 (대화 형 프롬프트에서 정의되지 않은 객체) 수입 된 개체에 대화 형 프롬프트에서 일 .

#print the class description 
print string.__doc__ 
#print function description 
print open.__doc__ 
+0

런타임에 생성되는 함수 (대화식 프롬프트 포함)에는 파일이나 줄 번호도 없으므로 의미가 있습니다 –

+0

그게 내가 원하는 것 같습니다. 감사! –

+6

앞에서 정의한 함수 정의를 현재 대화 형 Python 인터프리터에서 인쇄하는 방법은 무엇입니까? 이것이 가능한가? – GL2014

64
iPython를 사용하는 경우, 당신은 function_name?이 도움을받을 수 있습니다

function_name??는, 소스를 출력합니다. 이 기능을 가져 오는 경우

+3

+1, ipython은 멋지다! 당신은 그것에 링크를 추가 할 수 있습니다 : http://ipython.scipy.org/ – orip

+0

때로는 전화를 다른 라인으로 기능을 분리해야합니까? 예 : model.function ?? 작동하지 않지만 f = model.function; 에프?? 작동 – thecheech

-3

(내장에있는 개체, C libs와, 된 .pyc 파일 등에 그렇게되지 않음) 작동합니다 일반적으로 inspect이 좋은 대답이라는 데 동의하지만, 인터프리터에 정의 된 객체의 소스 코드를 가져올 수 없다는 것에 동의하지 않습니다. dill에서 dill.source.getsource을 사용하면 대화식으로 정의 된 경우에도 함수 및 lambda의 소스를 가져올 수 있습니다. 또한 카레에 정의 된 바운드 또는 언 바운드 클래스 메서드 및 함수에서 코드를 가져올 수 있지만 둘러싸는 객체 코드없이 해당 코드를 컴파일하지 못할 수도 있습니다. 당신은이 같은 hog()의 사용을 볼 수 있습니다 :

>>> from dill.source import getsource 
>>> 
>>> def add(x,y): 
... return x+y 
... 
>>> squared = lambda x:x**2 
>>> 
>>> print getsource(add) 
def add(x,y): 
    return x+y 

>>> print getsource(squared) 
squared = lambda x:x**2 

>>> 
>>> class Foo(object): 
... def bar(self, x): 
...  return x*x+x 
... 
>>> f = Foo() 
>>> 
>>> print getsource(f.bar) 
def bar(self, x): 
    return x*x+x 

>>> 
+1

그건 설명이 아니라 정의입니다. – Triptych

+0

(일반적으로 C 모듈에 정의 된 함수) 많은 내장 함수에 대해서는 함수 서명도 포함되지만 일반적으로 포함되지는 않습니다. – u0b34a0f6ae

+1

대화 형 셸에서 "help (object)"가 더 쉽게 탐색 할 수있는 방식으로 표시됩니다. –

8

: 파이썬 소스 코드를 찾을 수 있다면 물론 그것은 단지 당신은 __doc__ 키워드를 사용할 수 있습니다

+0

** getsource (my_function) **와 함께 작동하지 않는 경우가 있지만 ** getsource (my_function.func_code) ** – Afflatus

+0

또는 그 외의 방법으로 작동하도록 얻을 수 있습니다. getsource (my_function .__ code__) – Afflatus

+0

유휴 상태에서 작동하지 않는다 –

-3

당신은 함수에서 __doc__를 사용하는 예로서 hog() 기능을 취할 수

from skimage.feature import hog 

print hog.__doc__ 

출력은 다음과 같습니다

Extract Histogram of Oriented Gradients (HOG) for a given image. 
Compute a Histogram of Oriented Gradients (HOG) by 

    1. (optional) global image normalisation 
    2. computing the gradient image in x and y 
    3. computing gradient histograms 
    4. normalising across blocks 
    5. flattening into a feature vector 

Parameters 
---------- 
image : (M, N) ndarray 
    Input image (greyscale). 
orientations : int 
    Number of orientation bins. 
pixels_per_cell : 2 tuple (int, int) 
    Size (in pixels) of a cell. 
cells_per_block : 2 tuple (int,int) 
    Number of cells in each block. 
visualise : bool, optional 
    Also return an image of the HOG. 
transform_sqrt : bool, optional 
    Apply power law compression to normalise the image before 
    processing. DO NOT use this if the image contains negative 
    values. Also see `notes` section below. 
feature_vector : bool, optional 
    Return the data as a feature vector by calling .ravel() on the result 
    just before returning. 
normalise : bool, deprecated 
    The parameter is deprecated. Use `transform_sqrt` for power law 
    compression. `normalise` has been deprecated. 

Returns 
------- 
newarr : ndarray 
    HOG for the image as a 1D (flattened) array. 
hog_image : ndarray (if visualise=True) 
    A visualisation of the HOG image. 

References 
---------- 
* http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients 

* Dalal, N and Triggs, B, Histograms of Oriented Gradients for 
    Human Detection, IEEE Computer Society Conference on Computer 
    Vision and Pattern Recognition 2005 San Diego, CA, USA 

Notes 
----- 
Power law compression, also known as Gamma correction, is used to reduce 
the effects of shadowing and illumination variations. The compression makes 
the dark regions lighter. When the kwarg `transform_sqrt` is set to 
``True``, the function computes the square root of each color channel 
and then applies the hog algorithm to the image. 
+0

질문은 함수 정의가 함수 docstring이 아니었다. –

1

이것은 어떻게하는지 알아 냈습니다.

import inspect as i 
    import sys 
    sys.stdout.write(inspect.getsource(MyFunction)) 

새로운 줄 문자를 꺼내어 기능을 멋지게 출력합니다.

관련 문제