您的位置:首页 > 编程语言 > Python开发

Python基础-使用__slots__

2017-12-14 18:53 405 查看

slots

定义一个特殊的slots变量,来限制该class实例能添加的属性

不带 slots 的demo

示例

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# __slots__

class Student1(object):
pass

def runTest1():
s = Student1()
s.name = "蜡笔小新"
s.age = 6
s.score = 100
print("%s:%d:%d"%(s.name, s.age,s.score))

runTest1()


运行结果

D:\PythonProject\sustudy>python main.py
蜡笔小新:6:100


slots 的demo

示例

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

def runTest2():
s = Student2()
s.name = "蜡笔小新"
s.age = 6
s.score = 100
print("%s:%d:%d"%(s.name, s.age,s.score))

runTest2()


运行结果

Traceback (most recent call last):
File "main.py", line 30, in <module>
runTest2()
File "main.py", line 27, in runTest2
print("%s:%d:%d"%(s.name, s.age,s.score))
AttributeError: 'Student2' object has no attribute 'score'


由于限制了属性只有(‘name’, ‘age’) ,其他的属性将被限制(has no attribute ‘score’)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐