2

在以下 Python 代码中:

class Foo:
    def bar(self):
        return 1

def baz():
    return Foo()

print baz().bar()

问题0:

当在bar()中进行评估时print baz().bar(),是什么使Foo返回的实例baz()尚未被垃圾收集,因为似乎没有对它的引用,就像在:

foo = baz()
print foo.bar()

在哪里foo存储Foo实例的引用。

问题一:

如果 Foo 和 baz 在 Python 扩展模块中用 C 实现,是否应该baz增加返回对象的引用计数foo以将其设置为 1?

4

2 回答 2

3

答案 0:当bar()被调用时,bar 是一个绑定方法(绑定到Foo实例),它保持对其self参数的引用,即Foo实例。

于 2014-07-04T19:09:37.873 回答
0

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.

于 2014-07-04T20:09:40.097 回答