美文网首页
python class slots

python class slots

作者: 尹超_060d | 来源:发表于2018-06-01 09:50 被阅读0次
python 中的类的slots

因为python是动态语言,它允许在程序运行过程中给class实例绑定任何属性和方法
如果我们需要限制某个类的实例只允许有指定的几个属性或者方法,可以使用 slots 这个特殊变量

class testA(object):
        __slots__ = ("name", "age")

ta = testA()
ta.name = "me"
ta.male = "male"  # 该语句会报错...
报错信息
Traceback (most recent call last):
  File "d:\Learn-python\test.py", line 353, in <module>
    stuYc.male = "male"
AttributeError: 'Student' object has no attribute 'male'

相关文章

网友评论

      本文标题:python class slots

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