【问题标题】:Object creation and garbage collection in PythonPython中的对象创建和垃圾回收
【发布时间】:2017-04-30 16:19:17
【问题描述】:

请浏览下面的代码并解释我如何能够实现我共享的代码的输出:

class Customer:
    pass

c1=Customer()
print(c1)
print(Customer())
print(Customer(),Customer())
print(c1,Customer())
print(Customer())
print(Customer())

输出:

<__main__.Customer object at 0x0172FA90>
<__main__.Customer object at 0x0172FAB0>
<__main__.Customer object at 0x0172FAB0> <__main__.Customer object at  0x0172FB10>
<__main__.Customer object at 0x0172FA90> <__main__.Customer object at  0x0172FAB0>
<__main__.Customer object at 0x0172FAB0>
<__main__.Customer object at 0x0172FAB0>

【问题讨论】:

    标签: python python-3.x oop object garbage-collection


    【解决方案1】:

    对象的分配恰好使用相同的内存位置,这是不允许的。

    由于您创建的实例由于不存在引用而立即被收集,因此 Python 有机会重用相同的内存,这会导致其中一些具有相同的地址,请参见 documentation for the id() function

    返回对象的“身份”。这是一个整数,保证在其生命周期内对于该对象是唯一且恒定的。 生命周期不重叠的两个对象可能具有相同的id()

    (强调我的)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多