Python __slots__ 继承

Python __slots__ 继承教程

Python__slots__ 只能限制 实例属性 而不能限制 类属性,且如果在 继承 中使用 __slots__,那么 __slots__ 只能限制父类,不能限制子类的属性。

案例

Python slots 在继承中使用

使用 __slots__ 只能现在父类的属性列表

print("嗨客网(www.haicoder.net)") class Person: __slots__ = ('name', 'age') def __init__(self, name, age): self.name = name self.age = age person = Person("HaiCoder", 109) person.score = 99 print("Name =", person.name, "Age =", person.age, "Score =", person.score)

程序运行后,控制台输出如下:

99_python slots在继承中使用.png

我们使用 __slots__ 为 Person 类设置了类属性列表,即 Person 类只允许有 name 和 age 属性,接着,在程序中,我们为 Person 类的实例动态添加了一个 score 属性。

此时程序报错,因为,我们使用 __slots__ 为类的实例设置了属性限制后,无法再动态添加不在 __slots__ 元祖内的属性。我们将程序修改如下:

print("嗨客网(www.haicoder.net)") class Person: __slots__ = ('name', 'age') def __init__(self, name, age): self.name = name self.age = age class Student(Person): pass student = Student("HaiCoder", 109) student.score = 99 print("Name =", student.name, "Age =", student.age, "Score =", student.score)

程序运行后,控制台输出如下:

100_python slots在继承中使用.png

我们定义了一个 Student 类,Student 类继承自 Person 类,接着,我们实例化了 Student 类,并且给 Student 类的实例动态添加了 score 属性。

此时,score 属性不在 Student 类的父类 Person 的属性列表内,但程序没有报错,因为,__slots__ 不可以限制子类的实例属性,如果需要限制子类的实例属性,那么需要在子类中添加 __slots__ 限制,我们将程序修改如下:

print("嗨客网(www.haicoder.net)") class Person: __slots__ = ('name', 'age') def __init__(self, name, age): self.name = name self.age = age class Student(Person): __slots__ = ('name', 'age') student = Student("HaiCoder", 109) student.score = 99 print("Name =", student.name, "Age =", student.age, "Score =", student.score)

程序运行后,控制台输出如下:

101_python slots在继承中使用.png

我们在子类 Student 中,添加了 __slots__ 属性限制,此时,再次动态添加实例属性,程序报错。因此我们需要限制子类的属性列表,必须在子类中添加限制。

Python __slots__ 继承总结

Python 的 __slots__ 只能限制类的实例属性而不能限制类属性,且如果在继承中使用 __slots__,那么 __slots__ 只能限制父类,不能限制子类的属性。