Reputation: 2041
In the following Python code:
class Foo:
def bar(self):
return 1
def baz():
return Foo()
print baz().bar()
When bar()
is evaluated in print baz().bar()
, what make the Foo
instance returned by baz()
to have not yet been garbage collected, since it seems there is no reference to it, like there would be in:
foo = baz()
print foo.bar()
where foo
store a reference of the Foo
instance.
If Foo and baz were implemented in C in a Python extension module, should baz
increment the reference count of the returned object foo
to set it to 1?
Upvotes: 2
Views: 420
Reputation: 584
For part 0: Each time baz is called it creates a new object, Foo. You could see this by adding an init to Foo. So, before the print, the Foo instance does not exist. (It is not created when the function baz in declared, but only when it's called.
Part 1: As with 0, declaring baz() does not create an object. Calling baz() does. The reference count is incremented when 'Foo()' (Constructor) is called every time function baz is called.
Upvotes: 0
Reputation: 64298
Answer 0: when bar()
is called, bar is a bound method (bound to the Foo
instance), which keeps a reference to its self
argument, which is the Foo
instance.
Upvotes: 3