How does garbage collection in Python work with class methods?

class example:

    def exampleMethod(self):
        aVar = 'some string'
        return aVar

In this example, how does garbage collection work after each call to example.exampleMethod ()? Will aVar be freed after the method returns?

+3
source share
4 answers

A variable is never freed.

An object (in this case, a string with a value is 'some string'reused over and over, so the object can never be freed.

Objects are freed if no variable refers to the object. Think about it.

a = 'hi mom'
a = 'next value'

In this case, the first object (a string with a value 'hi mom') is no longer referenced anywhere in the script when the second statement is executed. Object ( 'hi mom') can be deleted from memory.

+6

, , .

a = MyObject() # +1, so it at 1
b = a # +1, so it now 2
a = 'something else' # -1, so it 1
b = 'something else' # -1, so it 0

MyObject, .

, .

, (.. , , dict).

cPython .

Python - , cPython - ( ) . Afaik , .

+4

, example.exampleMethod(), (, a = example.exampleMethod()), ( CPython), CPython . , . , . , dicts.

, CPython, Jython IronPython , // .. , , del(), ( ). - , :)

+3

, , , exampleMethod. Python ( CPython ) . aVar , aVar , , .

, ( del (self), " 1, " . gc - , 0. , , .

import gc
class Noisy(object):
    def __init__(self, n):
        self.n = n
    def __del__(self):
        print "Object " + str(self.n) + " being destructed"     
class example(object):
    def exampleMethod(self, n):
        aVar = Noisy(n)
        return aVar
a = example()
a.exampleMethod(1)
b = a.exampleMethod(2)
gc.collect()
print "Before b is deleted"
del b
gc.collect()
print "After b is deleted"

:

Object 1 being destructed
While b lives
Object 2 being destructed
After b is deleted

, Noisy , , 0, b, 0.

0

Source: https://habr.com/ru/post/1707999/


All Articles