python下__slots__属性使用

class Child(object):
    def __init__(self):
        self.name = 'zhou'

    def fun2(self):
        print 'fun1'

class Student(Child):
    __slots__ = ('name', 'id')
    id = 1

    def __init__(self):
        print 'init student'
        self.name = 'junjie'

stu = Student()

slots 限制了类的属性,我测试了一下,slots是限制了类里的成员变量,没有限制类里的类方法和类变量。
还有一点是,如果只在子类使用slots那么父类和子类的成员变量则不会被限制。就是如果slots只用在子类是无效的。

后面我执行了super(Child, self)后,slots里的限制生效了。
所以我猜测必须执行了父类的solts,该方法才会有效。

你可能感兴趣的:(python下__slots__属性使用)