zoukankan      html  css  js  c++  java
  • Python __slots__

    Python 类的特殊变量:__slots__

    使用 __slots__ 后,类中 __weakref____dict__ 消失,同时阻止动态属性绑定
    由于 __dict__ 记录着类中所有的属性,占用空间比较多,所以可以在大量实例存在时节省内存空间

    class Test1(object):
        __slots__ = ['attr1', 'attr2']
    
        def __init__(self, attr1, attr2):
            self.attr1 = attr1
            self.attr2 = attr2
    
    
    class Test2(object):
        def __init__(self, attr1, attr2):
            self.attr1 = attr1
            self.attr2 = attr2
    
    
    if __name__ == '__main__':
        test1 = Test1('attr1', 'attr2')
        print(Test1.__dict__)
        
        test2 = Test2('attr1', 'attr2')
        test2.attr3 = 'attr3'
        Test2.attr4 = 'attr4'
        print(test2.__dict__)
        print(Test2.__dict__)
    
    

    继承的子类如果不使用 __slots__ 并不受影响,如果使用则允许定义的是本身的 __slots__ 加上父类的 __slots__

  • 相关阅读:
    词向量的发展
    拉格朗日对偶理解
    EM算法理解
    Xgboost理解
    GBDT理解
    深入理解KS
    PCA主成分分析理解
    SVM理解
    Python调用C++
    Linux opencv安装与编译
  • 原文地址:https://www.cnblogs.com/dbf-/p/11384995.html
Copyright © 2011-2022 走看看