因为python为动态语言,处理变量的方式与一些静态语言(比如C++)不大一样,在这里对这些变量进行小小的总结?
python中全局变量与C语言中类似,也就是在的那个单页面所有函数外头定义的变量?
局部变量为函数内定义的变量,函数执行完后会被回收?
实例变量是类中前面有self的变量,每个实例变量都不同?
类变量是所有实例共享的一个变量,所有实例占同一个内存?
来看个程序就懂了!?
>>> big_temp = '123456788'? # 全局变量
>>> class Test:
? ? global_temp = '123'? ? ?# 类变量
? ? def __init__(self):
? ? ? ? self.temp = '321'? ?# 实例变量
? ? ? ? mytemp = '345'? ? ? # 局部变量
? ? def print_something(self,a):
? ? ? ? print(self.temp)
? ? ? ? print(a)
>>> test = Test()
>>> test.__dict__
>>> Out[10]: {'temp': '321'}
>>> test.global_temp = '123456'
>>> test.__dict__
Out[12]: {'global_temp': '123456', 'temp': '321'}
>>> Test.global_temp
Out[13]: '123'
>>> test.print_something(big_temp)
321
123456788
本文系转载,前往查看
如有侵权,请联系?cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系?cloudcommunity@tencent.com 删除。