美文网首页
python __slots__

python __slots__

作者: 任我笑笑 | 来源:发表于2018-04-23 17:25 被阅读0次

    url https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186739713011a09b63dcbd42cc87f907a778b3ac73000

    一个没见过的属性,限制实例随意扩展,只对当前实例有效


    使用slots
    但是,如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加name和age属性。

    为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的slots变量,来限制该class实例能添加的属性:

    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'
    

    由于'score'没有被放到slots中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。

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

    class GraduateStudent(Student):
    ...     pass
    ...
    g = GraduateStudent()
    g.score = 9999
    

    除非在子类中也定义slots,这样,子类实例允许定义的属性就是自身的slots加上父类的slots

    相关文章

      网友评论

          本文标题:python __slots__

          本文链接:https://www.haomeiwen.com/subject/qcvllftx.html