首页 > 编程语言 > 详细

python 面向对象编程的__slots__

时间:2020-07-15 15:54:03      阅读:58      评论:0      收藏:0      [点我收藏+]

同一个类下,不同实例定义的属性或者方法,其他实例如果没有定义是不能使用的

#定义一个类
class Student(object):
    pass


#给类绑定一个实例
s=Student()

#给实例绑定一个属性
s.name=Micheal
s.name   #‘Micheal‘

s1=Student()
s1.name    #报错AttributeError: ‘Student‘ object has no attribute ‘name‘ 

我们如果想要给所有实例都绑定属性或者方法,只需给类绑定属性或者方法就可以了,这样所有的实例都可以调用

但是我们想要限制实例的属性,比如说实例只能添加name和age属性

在定义类时,使用__slots__变量,来限制类实例能添加的属性

__slots__变量的使用方法

class Student(object):
    __slots__ = (name, age) # 用tuple定义允许绑定的属性名称



s = Student() # 创建新的实例
s.name = Michael # 绑定属性‘name‘
s.age = 25 # 绑定属性‘age‘
s.score = 99 # 绑定属性‘score‘
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Student object has no attribute score

要注意的是,__slots__变量定义的属性仅对当前类的实例起作用,对继承的子类的实例是不起作用的

 class GraduateStudent(Student):
     pass

 g = GraduateStudent()
 g.score = 9999  #这样是没有问题的

 

python 面向对象编程的__slots__

原文:https://www.cnblogs.com/cgmcoding/p/13305318.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!