cat.py
# !/usr/bin/python3
# coding: utf-8
ear = 0
dog.py
# !/usr/bin/python3
# coding: utf-8
class Dog(object):
leg = 0
def __init__(self, num):
# 类变量
Dog.leg = num
run.py
# !/usr/bin/python3
# coding: utf-8
import cat
from dog import Dog
mouth = 0
def main():
Dog(4)
print(Dog.leg)
cat.ear = 2
print(cat.ear)
global mouth
mouth = 1
print(mouth)
if __name__ == "__main__":
main()
全局变量分别是狗腿(dog.leg)、猫耳(cat.ear)和嘴(mouth)的数量
测试
# !/usr/bin/python3
# coding: utf-8
from sys import getrefcount
import cat
from dog import Dog
mouth = 0
def main():
Dog(4)
print("Dog.leg=%s, refCount=%s" % (Dog.leg, getrefcount(Dog.leg)))
cat.ear = 2
print("cat.ear=%s, refCount=%s" % (cat.ear, getrefcount(cat.ear)))
global mouth
mouth = 1
print("mouth=%s, refCount=%s" % (mouth, getrefcount(mouth)))
if __name__ == "__main__":
main()
结果
Dog.leg=4, refCount=332
cat.ear=2, refCount=888
mouth=1, refCount=1921
引用越多越难回收