Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 라이브 객체 검사

<시간/>

이 모듈의 함수는 모듈, 클래스, 메소드, 함수, 코드 객체 등과 같은 라이브 객체에 대한 유용한 정보를 제공합니다. 이러한 함수는 유형 검사를 수행하고, 소스 코드를 검색하고, 클래스 및 함수를 검사하고, 인터프리터 스택을 검사합니다.

getmembers()- 이 함수는 이름, 이름별로 정렬된 값 쌍의 목록에 있는 개체의 모든 구성원을 반환합니다. 선택적 술어가 제공되면 술어가 true 값을 리턴하는 멤버만 포함됩니다. getmodulename() -이 함수는 둘러싸는 패키지의 이름을 포함하지 않고 파일 경로에 의해 명명된 모듈의 이름을 반환합니다.

inspect 모듈의 동작을 이해하기 위해 다음 스크립트를 사용할 것입니다.

#inspect-example.py'''이것은 모듈 독스트링'''def hello():'''hello docstring''' print ('Hello world') return#class 정의class parent:'''parent docstring ''' def __init__(self):self.var='hello' def hello(self):print (self.var)class child(parent):def hello(self):'''hello 함수 재정의''' super ().hello() print("잘 지내세요?")

'__'로 시작

>>> import inspect, inspect_example>>> k,v in inspect.getmembers(inspect_example):if k.startswith('__')==False:print (k,v)childhelloparent>>> 

술어

술어는 inspect 모듈의 기능에 적용되는 논리적 조건입니다. 예를 들어 getmembers() 함수는 주어진 술어 조건이 참인 모듈의 멤버 목록을 반환합니다. 다음 술어는 inspect 모듈에 정의되어 있습니다.

ismodule() 객체가 모듈이면 true를 반환합니다.
isclass() 객체가 클래스이면 내장 또는 Python 코드로 생성된 경우 true를 반환합니다.
ismmethod() 객체가 Python으로 작성된 바인딩된 메서드인 경우 true를 반환합니다.
기능() 객체가 람다 식으로 생성된 함수를 포함하는 Python 함수인 경우 true를 반환합니다.
isgenerator() 객체가 제너레이터이면 true를 반환합니다.
iscode() 객체가 코드이면 true를 반환합니다.
isbuiltin() 객체가 내장 함수이거나 바인딩된 내장 메서드이면 true를 반환합니다.
isabstract() 객체가 추상 기본 클래스이면 true를 반환합니다.

여기에서는 모듈의 클래스 멤버만 반환됩니다.

>>> for k,v in inspect.getmembers(inspect_example, inspect.isclass):print (k,v)child parent >>> 

지정된 클래스 '자식'의 구성원을 검색하려면 -

>>> inspect.getmembers(inspect_example.child)>>> x=inspect_example.child()>>> inspect.getmembers(x)

getdoc() 함수는 모듈, 클래스 또는 함수의 독스트링을 검색합니다.

>>> inspect.getdoc(inspect_example)'이것은 모듈 독스트링'>>> inspect.getdoc(inspect_example.parent)'부모 독스트링'>>> inspect.getdoc(inspect_example.hello)'안녕 독스트링' 

getsource() 함수는 함수의 정의 코드를 가져옵니다 -

>>> print (inspect.getsource(inspect_example.hello))def hello():'''hello docstring''' print ('Hello world') return>>> sign=inspect.signature(inspect_example.parent .hello)>>> 인쇄(서명)

inspect 모듈에는 명령줄 인터페이스도 있습니다.

C:\Users\acer>python -m inspect -d inspect_exampleTarget:inspect_exampleOrigin:C:\python36\inspect_example.pyCached:C:\python36\__pycache__\inspect_example.cpython-36.pycLoader:<_Frozen.import00BD000에서 Source29Loader0>

다음 명령은 모듈에서 'Hello()' 함수의 소스 코드를 반환합니다.

C:\Users\acer>python -m inspect inspect_example:hellodef hello():'''hello docstring''' print('Hello world') 반환