小白学python之使用__slots__学习笔记

本文以廖雪峰的官方网站为参考来学习python的。其学习链接为廖雪峰小白学python教程

本文是学习到python的实例属性和类属性。参考链接廖雪峰python使用__slot__

尝试给实例绑定一个属性:

class Student(object):
    pass
s = Student()
s.name = 'Michael'
print(s.name)

运行结果: Michael

尝试给实例绑定一个方法:

def set_age(self, age):
    self.age = age

from types import MethodType
s.set_age = MethodType(set_age, s)
s.set_age(25)
print(s.age)

运行结果: 25

 

笔记

给一个实例绑定的方法,对另一个实例是不起作用的:

s2 = Student()
s2.set_age(25)

运行结果,报错:

Traceback (most recent call last):
  File "**********", line **, in <module>
    s2.set_age(25)
AttributeError: 'Student' object has no attribute 'set_age'

def set_score(self, score):
    self.score = score

Student.set_score= set_score
s.set_score(100)
print(s.score)

s2.set_score(99)
print(s2.score)

笔记

给class绑定方法后,所有实例均可调用。

通常情况下,上面的set_score方法可以直接调用在class中。但动态绑定允许我们在程序运行过程中动态给class加上功能,这在静态语言中很难实现。

使用__slot__

class Student(object):
    __slots__=('name','age')
s = Student()
s.name = 'Michael'
s.age = 25
#print(s.name,s.age)
s.score = 99

运行结果,报错:

Traceback (most recent call last):
  File "*********", line ***, in <module>
    s.score = 99
AttributeError: 'Student' object has no attribute 'score'

笔记

Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性。

__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章