监听对象的生命周期
# -----------------------------几个监听对象生命周期的方法----------------------
# class Person:
# # def __new__(cls, *args, **kwargs):
# # print("新建一个对象,但是被我拦截了")
# def __init__(self):
# print("初始化方法")
# self.name = "sz"
#
# def __del__(self):
# print("这个对象被释放了")
# p = Person()
# print(p)
# print(p.name)
# --------------------------监听对象生命周期的方法-小案例-------------------------
# Person, 打印一下,当前这个时刻,由Person类,产生的实例,有多少个
# 创建了一个实例,计数+1,删除一个实例,计数 -1
class Person:
__personCount = 0
def __init__(self):
print("计数 + 1")
Person.__personCount += 1
def __del__(self):
print("计数 - 1")
self.__class__.__personCount -= 1
# @staticmethod
# def log():
# print("当前的人的个数是%d个" % Person.__personCount)
@classmethod
def log(cls):
print("当前的人的个数是%d个" % cls.__personCount)
p = Person()
p2 = Person()
Person.log()
del p
Person.log()
内存管理机制
class Person:
pass
p = Person()
# print(p)
# print(id(p))
# print(hex(id(p)))
p2 = Person()
print(id(p), id(p2))
# -----------------------引用计数器-------------------------------------
import sys
class Person:
pass
p1 = Person()
print(sys.getrefcount(p1))
p2 = p1
print(sys.getrefcount(p1))
del p2
del p1
# ---------------------------引用计数器 +1 -1 的场景举例
import sys
class Person:
pass
p = Person() #1
print(sys.getrefcount(p))
# def log(obj):
# print(sys.getrefcount(obj))
# log(p)
l = [p]
print(sys.getrefcount(p))
# -----------------------引用计数器机制-特殊场景-循环应用问题------------------------
# 内存管理机制 = 引用计数器机制 + 垃圾回收机制
# 当一个对象,如果被引用 + 1,删除一个引用:-1 0:自动释放
# 循环引用
# objgraph.count 可以查看垃圾回收器,跟踪的对象个数
import objgraph
class Person:
pass
class Dog:
pass
p = Person()
d = Dog()
print(objgraph.count("Person"))
print(objgraph.count("Dog"))
p.pet = d
p.master = p
del p
del d
print(objgraph.count("Person"))
print(objgraph.count("Dog"))
垃圾回收机制
import gc
print(gc.get_threshold())
gc.set_threshold(200, 5, 5)
print(gc.get_threshold())
#---------------------垃圾回收机制-触发时机-------------------------------
# import gc
# gc.disable()
# print(gc.isenabled())
# gc.enable()
# print(gc.isenabled())
#
# print(gc.get_threshold())
# 手动回收
import objgraph
import gc
class Person:
pass
class Dog:
pass
p = Person()
d = Dog()
p.pet = d
d.master = p
del p
del d
gc.collect()
print(objgraph.count("Person"))
print(objgraph.count("Dog"))
# ------------循环引用-细节问题(版本兼容方案)------------------------
import objgraph
import gc
import weakref
# 1.定义了两个类
class Person:
def __del__(self):
print("Person对象,被释放了")
pass
class Dog:
def __del__(self):
print("Dog对象,被释放了")
pass
# 2.根据这两个类,创建出两个实例
p = Person()
d = Dog()
# 3.让两个实例对象之间相互引用,造成循环
# p.pet = d
p.pets = {"dog": weakref.ref(d1), "cat": weakref.ref(c1)}
weakref.WeakValueDictionary({"dog": d1, "cat":c1})
# d.master = weakref.ref(p)
d.master = p
# 4.尝试删除可到达引用之后,测试真实对是否又被回收
p.pet = None
del p
del d
# 5.通过"引用计数机制"无法回收,需要借助"垃圾回收机制"进行回收
# gc.collect()
print(objgraph.count("Person"))
print(objgraph.count("Dog"))