当前位置:Gxlcms > Python > python内存释放原则

python内存释放原则

时间:2021-07-01 10:21:17 帮助过:54人阅读

  1. def getInit(class_name):
  2. """动态加载模块"""
  3. resultmodule = __import__(class_name, globals(), locals(), [class_name])
  4. resultclass = getattr(resultmodule, class_name)
  5. return resultclass()
  6. import threading, time
  7. class b:
  8. def __init__(self, *args, **kwargs):
  9. self.name = "b"
  10. self.class_name = "a"
  11. print "%s is inited" % (self.name)
  12. def __del__(self):
  13. print "%s is deleted" % (self.name)
  14. def other_run(self, obj=None):
  15. if obj:
  16. obj.run()
  17. def run(self, *args, **kwargs):
  18. obj = getInit(self.class_name)
  19. obj.run()
  20. self.other_run(obj)
  21. print "%s is run" % (self.name)
  22. def treading():
  23. n = 0
  24. c = b()
  25. while n<2:
  26. n += 1
  27. print "\n"
  28. print "start"
  29. c.run()
  30. print "end"
  31. print "\n"
  32. if __name__ == '__main__':
  33. param = {}
  34. th = threading.Thread(target = treading, args = ())
  35. th.start()
  36. exit()
  1. b is inited
  2. start
  3. a is inited
  4. a is run
  5. a is run
  6. b is run
  7. a is deleted
  8. end
  9. start
  10. a is inited
  11. a is run
  12. a is run
  13. b is run
  14. a is deleted
  15. end
  16. b is deleted

每个循环内都把a重新加载并且释放内存

  1. def getInit(class_name):
  2. resultmodule = __import__(class_name, globals(), locals(), [class_name])
  3. resultclass = getattr(resultmodule, class_name)
  4. return resultclass()
  5. import threading, time
  6. import a
  7. class b:
  8. def __init__(self, *args, **kwargs):
  9. self.name = "b"
  10. self.class_name = "a"
  11. self.obj = getInit(self.class_name)
  12. print "%s is inited" % (self.name)
  13. def __del__(self):
  14. print "%s is deleted" % (self.name)
  15. def other_run(self):
  16. if self.obj:
  17. self.obj.run()
  18. def run(self, *args, **kwargs):
  19. self.obj.run()
  20. self.other_run()
  21. print "%s is run" % (self.name)
  22. def treading():
  23. n = 0
  24. c = b()
  25. while n<2:
  26. n += 1
  27. print "\n"
  28. print "start"
  29. c.run()
  30. print "end"
  31. print "\n"
  32. if __name__ == '__main__':
  33. param = {}
  34. th = threading.Thread(target = treading, args = ())
  35. th.start()
  36. exit()
  1. a is inited
  2. b is inited
  3. start
  4. a is run
  5. a is run
  6. b is run
  7. end
  8. start
  9. a is run
  10. a is run
  11. b is run
  12. end
  13. b is deleted
  14. a is deleted

最后结束a才释放


内存释放是根据指向的

人气教程排行