Python __slots__ 使用

Python __slots__ 使用教程

Python 是动态语言,因此,在创建了一个 类实例 后,我们可以给该实例绑定任何 属性方法,也就是给属性动态的添加属性和方法。

如果我们想要限制 Python 中 的属性,Python 允许在定义类的时候,定义一个特殊的 __slots__ 变量,来限制该类的实例能添加的属性。

注意:Python 的 __slots__ 只能限制类的实例属性不能限制类属性。

Python __slots__ 详解

语法

__slots__ = ('name', 'age')

说明

元祖 定义允许绑定的属性的名称,不在元祖内的属性,不可以动态的添加。

案例

Python 动态添加类属性

使用 __slots__ 不可以限制动态添加的类属性

print("嗨客网(www.haicoder.net)") class Person: course = "Python" def __init__(self, name, age): self.name = name self.age = age person = Person("HaiCoder", 109) print("Name =", person.name, "Age =", person.age, "Course =", Person.course)

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

94_python slots使用.png

我们定义了一个 Person 类,Person 类有一个类属性和两个实例属性,接着,我们实例化了一个 Person 类,并使用 构造函数 设置了实例属性 name 和 age 的值。

最后,我们分别使用实例访问了实例属性 name 和 age 的值,以及使用类名访问了类属性的值。我们将程序修改如下:

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

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

95_python slots使用.png

我们为程序添加了一个类属性 score,并使用类名访问了该类属性,此时,再次运行程序,程序正常输出了我们添加的类属性的值。我们再次将程序修改如下:

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

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

96_python slots使用.png

我们在类 Person 里,使用 __slots__ 修饰了类 Person 的属性列表只有 name 和 age,接着,我们给类动态添加了一个类属性 score。

此时,再次运行程序,程序运行正常,因此,类的 __slots__ 属性不可以限制动态添加的类属性。

Python 动态添加实例属性

使用 __slots__ 不可以限制动态添加的实例属性

print("嗨客网(www.haicoder.net)") class Person: 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)

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

97_python slots使用.png

我们定义了一个 Person 类,Person 类有两个实例属性,接着,我们实例化了一个 Person 类,并使用构造函数设置了实例属性 name 和 age 的值,同时,我们为 Person 实例添加了一个动态实例属性 score。

最后,我们分别使用实例访问了实例属性 name 和 age 的值以及 score 的值,我们将程序修改如下:

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)

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

98_python slots使用.png

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

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

Python __slots__ 使用总结

Python 是动态语言,因此,在创建了一个类实例后,我们可以给该实例绑定任何属性和方法,也就是给属性动态的添加属性和方法。

如果我们想要限制 Python 中类的属性,Python 允许在定义类的时候,定义一个特殊的 __slots__ 变量,来限制该类的实例能添加的属性。

注意:Python 的 __slots__ 只能限制类的实例属性不能限制类属性。