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’)
相关文章推荐
- python基础——使用__slots__
- Python基础(6)- 类和对象(使用、继承、派生、组合、接口、多态、封装、property、staticmethod、classmethod、反射、slots、上下文管理协议、元类)
- python-math-基础使用
- 对象使用self注意事项 分类: python基础学习 2013-09-03 09:52 218人阅读 评论(0) 收藏
- python __slots__ 使用
- 使用os.popen/commands.getoutput查询指定端口号的服务 分类: python 小练习 open()文件读写 python基础学习 2013-09-17 17:49 798人阅读 评论(0) 收藏
- Python连载系列之Python语法基础1:开始使用Python
- python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
- python基础教程之python消息摘要算法使用示例
- 使用文件进行优化 分类: python 小练习 divide into python python基础学习 2014-01-01 14:13 228人阅读 评论(0) 收藏
- python基础教程之lambda表达式使用方法
- python基础教程之类class定义使用方法
- python基础教程之类class定义使用方法
- 使用生成器返回fibs列表 分类: python Module python基础学习 2013-10-28 18:19 283人阅读 评论(0) 收藏
- Python中单/双下划线使用 分类: python python基础学习 2013-09-02 21:31 1764人阅读 评论(0) 收藏
- python数据持久存储:pickle模块的基本使用 分类: python python基础学习 python 小练习 2013-06-17 14:41 209人阅读 评论(0) 收藏
- Python基础学习篇——Global全局变量的使用
- python基础:用apply使用元祖和列表调用函数
- Linux Python基础知识学习,使用Eclipse与Pydev搭建python开发环境
- 在python中使用pdb基础调试