# 1. 走向毁灭的函数循环调用

>>> def a():
print('我是a')
b()

>>> def b():
print('我是b')
a()

>>> a()


>>> a()

...... # 此处省略了一千余行
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
a()
File "<pyshell#59>", line 3, in a
b()
...... # 此处省略了两千余行
RecursionError: maximum recursion depth exceeded while pickling an object


RecursionError: maximum recursion depth exceeded while pickling an object

>>> import sys
>>> sys.getrecursionlimit()
1000
>>> sys.setrecursionlimit(500)
>>> sys.getrecursionlimit()
500


# 2. 同生共死的对象循环引用

>>> import sys
>>> a = list('abc')
>>> sys.getrefcount(a)
2
>>> b = a
>>> sys.getrefcount(a)
3
>>> del b
>>> sys.getrefcount(a)
2


class A:
def __init__(self, name, somebody=None):
self.name = name
self.somebody = somebody
print('%s: init'%self.name)
def __del__(self):
print('%s: del'%self.name)

a = A('a')
b = A('b')

del a
del b

print('运行结束')


a: init
b: init
a: del
b: del

class A:
def __init__(self, name, somebody=None):
self.name = name
self.somebody = somebody
print('%s: init'%self.name)
def __del__(self):
print('%s: del'%self.name)

a = A('a')
b = A('b')

a.somebody = b
b.sombody = a

del a
del b

print('运行结束')


a: init
b: init

a: del
b: del

import gc

class A:
def __init__(self, name, somebody=None):
self.name = name
self.somebody = somebody
print('%s: init'%self.name)
def __del__(self):
print('%s: del'%self.name)

a = A('a')
b = A('b')

a.somebody = b
b.sombody = a

del a
del b

gc.collect()

print('运行结束')


a: init
b: init
a: del
b: del

# 3. 转圈推磨的模块循环导入

import b

MODULE_NAME = 'a'
print(b.MODULE_NAME)


import a

MODULE_NAME = 'b'
print(a.MODULE_NAME)


Traceback (most recent call last):
File “a.py”, line 1, in
import b
File “D:\temp\csdn\b.py”, line 1, in
import a
File “D:\temp\csdn\a.py”, line 4, in
print(b.MODULE_NAME)
AttributeError: module ‘b’ has no attribute ‘MODULE_NAME’

02-17 3万+