python类变量和实例变量区别
在python tutorial中对于类变量和实例变量是这样描述的:
Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
通常来说,实例变量是对于每个实例都独有的数据,而类变量是该类所有实例共享的属性和方法。(推荐学习:Python视频教程)
它们区别在于:实例变量为所属对象所私有,而类变量为所有对象所共有
类变量又叫全局变量,是属于类的特性,实例先找实例化变量,然后再去找类变量. 但是实例变量只是属于实例化的变量, 但是类变量也可以用实例去调用. 如果类变量有多重继承关系, 就需要按照指定的路线进行查找. 先看看代码理解下吧
立即学习“Python免费学习笔记(深入)”;
class A: aa=10 def __init__(self,a,b): self.a=a self.b=ba=A(5,20)print(a.a) #实例变量print((a.aa))#实例读取类变量#打印结果 510
更多Python相关技术文章,请访问Python教程栏目进行学习!