您当前的位置: 首页 >  Python

84 python高级 - __slots__

杨林伟 发布时间:2019-08-19 09:32:12 ,浏览量:1

动态语言: 可以在运行的过程中,修改代码

静态语言: 编译时已经确定好代码,运行过程中不能修改

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

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

>>> class Person(object):
    __slots__ = ("name", "age")

>>> P = Person()
>>> P.name = "老王"
>>> P.age = 20
>>> P.score = 100
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: Person instance has no attribute 'score'
>>>
注意:

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

In [67]: class Test(Person):
    ...:     pass
    ...:

In [68]: t = Test()

In [69]: t.score = 100
关注
打赏
1688896170
查看更多评论

杨林伟

暂无认证

  • 1浏览

    0关注

    3183博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0968s