首页 > 代码库 > python 类变量和实例变量

python 类变量和实例变量

实例的属性存储在实例的__dict__中,类属性和方法存储在类的__dict__中.查找属性时,先检查特性,然后实例的__dict__,然后类的__dict__,然后基类.都不存在就会抛出异常.
print ‘***************************************************‘
class AA:
    count = 0
    def __init__(self):
        pass
    def AddCount(self):
        print ‘id -> self.__class__.count  self.count‘
        print id(self.__class__.count)
        print id(self.count)
        print self.count
        self.__class__.count = self.__class__.count + 1
        print ‘----------id after class assign--------‘
        print ‘id -> self.__class__.count  self.count‘
        print id(self.__class__.count)
        print id(self.count)
        print self.count
        self.count = self.count + 1
        print ‘----------id after instance assign--------‘
        print id(self.count)
if __name__ == "__main__":
    print id(AA.count)
    a = AA()
    a.AddCount()
    print a.count
    print ‘***************************************************‘
    b = AA()
    b.AddCount()
    print b.count
***************************************************
8207488
id -> self.__class__.count  self.count
8207488
8207488
0
----------id after class assign--------
id -> self.__class__.count  self.count
8207464
8207464
1
----------id after instance assign--------
8207440
2
***************************************************
id -> self.__class__.count  self.count
8207464
8207464
1
----------id after class assign--------
id -> self.__class__.count  self.count
8207440
8207440
2
----------id after instance assign--------
8207416
3

python 类变量和实例变量