zoukankan      html  css  js  c++  java
  • python 面向对象编程的__slots__

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

    #定义一个类
    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  #这样是没有问题的
  • 相关阅读:
    20200924-3 单元测试,结对
    20200924-1 每周例行报告
    20200924-5 四则运算试题生成,结对
    20200924-2 功能测试
    20200924-4 代码规范,结对要求
    20200929-git地址
    20200917-1 每周例行报告
    20200917-2 词频统计
    20200917-3 白名单
    20200910-2 博客作业
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/13305318.html
Copyright © 2011-2022 走看看