logo

Python의 소멸자

사용자는 객체를 파괴하기 위해 소멸자를 호출합니다. Python에서는 개발자에게 C++ 언어에서 필요한 만큼 소멸자가 필요하지 않을 수 있습니다. Python에는 자동으로 메모리 관리를 처리하는 기능을 갖춘 가비지 수집기가 있기 때문입니다.

이 기사에서는 Python의 소멸자가 어떻게 작동하고 사용자가 이를 언제 사용할 수 있는지 논의합니다.

그만큼 __의__() 함수는 소멸자 함수로 사용됩니다. 파이썬 . 사용자는 __의__() 객체의 모든 참조가 삭제되면 함수가 가비지 수집됩니다.

통사론:

 def __del__(self): # the body of destructor will be written here. 

또한 사용자는 객체가 참조를 벗어나거나 코드가 끝나면 객체에 대한 참조도 삭제된다는 점에 유의해야 합니다.

다음 예제에서는 소멸자가 자동으로 포함되도록 객체의 모든 참조를 삭제하기 위해 __del__() 함수와 del 키워드를 사용합니다.

예를 들어:

 # we will illustrate destructor function in Python program # we will create Class named Animals class Animals: # we will initialize the class def __init__(self): print('The class called Animals is CREATED.') # now, we will Call the destructor def __del__(self): print('The destructor is called for deleting the Animals.') object = Animals() del object 

산출:

 The class called Animals is CREATED. The destructor is called for deleting the Animals. 

설명 -

위 코드에서는 객체에 대한 참조가 삭제되거나 프로그램이 종료된 후에 소멸자가 호출되었습니다. 이는 개체가 범위를 벗어날 때 개체의 참조 횟수가 0이 되고 개체가 범위를 벗어나는 경우가 아니라는 것을 의미합니다. 다음 예를 보여줌으로써 이에 대해 설명하겠습니다.

프로그램 종료 후에 소멸자가 호출되는 것도 확인할 수 있습니다.

예:

 # We will create Class named Animals class Animals: # Initialize the class def __init__(self): print('The class called Animals is CREATED.') # now, we will Call the destructor def __del__(self): print('The destructor is called for deleting the Animals.') def Create_object(): print('we are creating the object') object = Animals() print('we are ending the function here') return object print('we are calling the Create_object() function now') object = Create_object() print('The Program is ending here') 

산출:

 we are calling the Create_object() function now we are creating the object The class called Animals is CREATED. we are ending the function here The Program is ending here The destructor is called for deleting the Animals. 

이제 다음 예제에서는 function()이 호출되면 Zebra 클래스의 인스턴스가 생성되고 Lion 클래스에 자신을 전달한 다음 Zebra 클래스에 대한 참조를 설정하고 결과는 다음과 같습니다. 순환 참조.

예:

 class Animals: # we will initialize the class def __init__(self): print(' The class called Animals is CREATED.') class Lion: def __init__(self, zebraa): self.zebra = zebraa class Zebra: def __init__(self): self.lion = Lion(self) def __del__(self): print('Zebra is dead') def function(): zebra = Zebra() function() 

산출:

 Zebra is dead 

일반적으로 이러한 유형의 순환 참조를 감지하는 데 사용되는 Python의 가비지 수집기도 참조를 제거합니다. 그러나 위의 예에서는 이 항목을 수집 불가능으로 표시하기 위해 사용자 지정 소멸자가 사용되었습니다.

쉽게 말하면 가비지 컬렉터가 객체가 어떤 순서로 파괴되어야 하는지 모르기 때문에 그대로 놔두는 것을 의미합니다. 따라서 사용자 인스턴스가 이 순환 참조에 포함되어 있으면 응용 프로그램이 실행되는 동안 메모리에 계속 저장됩니다.

결론

이 기사에서는 Python에서 소멸자의 기능과 사용자가 참조가 메모리에서 이미 제거된 객체를 삭제하는 데 이를 사용하는 방법을 설명했습니다.