-1

Given the code sample below, what is the life cycle for bb in in example 1 and for self.bb in example 2

Example 1

import B

class A:
    def __init__( self ):
        bb = B( self )

Example 2

import B

class A:

    def __init__( self ):
        self.bb = B( self )

Edit:

B is another class and for some reason i found it was not garbage collected in the first example. I looked more carefully in my code and i found out B class created a new class C and gave a ref to one of its methods to that C class. In the end C instantiated a loop back thread to wait for events hence B class instance was still alive even though A class init was done.

Thanks all for your answers.

  • 3
    Neither `bb` has **any** lifetime, since you are not creating instances of class A. `bb` in the first example is a local; like all locals it is cleaned up the moment `A.__init__` exits. Your question is rather broad and answered in the Python documentation and elsewhere on Stack Overflow though; what research have you done yourself and what wasn't clear? – Martijn Pieters Jan 28 '15 at 08:20

3 Answers3

0

On both cases there will be no reference to the B instance until you instantiate A.

Once you instantiate A, in the first case it will be discarded right after __init__ runs because bb will be out of scope and there will be no reference left to that B instance, so it will be garbage-collected on the next GC cycle (exactly when is an implementation detail). On the second case, the reference to that B instance will exist as long as a reference for the A instance exists or until you manually remove it.

Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
0

In first example bb is local variable for function __init__ The bb variable can access within the same __init__ function.

In 2nd example self.bb is Instance variables for every class object.

Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
-2

They has not any life-time. You have to inherited.

Example 1

import B
class A:
    def __init__( self ):
        B.__init__(self)
bb = B()

Example 2

import B
class A:
    def __init__( self ):
        B.__init__(self)

bb = B()

For more information about init

Community
  • 1
  • 1