python基础——使用__slots__
python基础——使用__slots__
正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。先定义class:
class Student(object):
pass
然后,尝试给实例绑定一个属性:
>>> s = Student()
>>> s.name = 'Michael' # 动态给实例绑定一个属性
>>> print(s.name)
Michael
还可以尝试给实例绑定一个方法:
>>> def set_age(self, age): # 定义一个函数作为实例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25
但是,给一个实例绑定的方法,对另一个实例是不起作用的:
>>> s2 = Student() # 创建新的实例
>>> s2.set_age(25) # 尝试调用方法
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'set_age'
为了给所有实例都绑定方法,可以给class绑定方法:
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = set_score
给class绑定方法后,所有实例均可调用:
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99)
>>> s2.score
99
通常情况下,上面的set_score方法可以直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能,这在静态语言中很难实现。
使用__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__ 示例
#2016-8-29 21:25:14
#MengmengCoding
# -*- coding: utf-8 -*- #使用__slots__限制实例的属性 class Student(object):
__slots__=('name','age') #用tuple定义允许绑定的属性名称 #新类,继承于Student
class GraduateStudent(Student):
pass s=Student() #创建新的实例
s.name='Shuke' #绑定属性'name'
s.age=25 #绑定属性'age' # ERROR: AttributeError: 'Student' object has no attribute 'score'
try:
s.score=99
except AttributeError as e:
print('AttributeError:',e) g=GraduateStudent() #创建新的实例
'''
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,
对继承的子类是不起作用的
'''
g.score=99 #绑定属性'score'
print('g.score=',g.score)
python基础——使用__slots__的更多相关文章
- Python基础(__slots__)
class Point(object): __slots__ = ('name','point') p1 = Point() p1.name = 100 print(p1.name)#100 #p1. ...
- python基础——定制类
python基础——定制类 看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的. __slots__我们已经知道怎么用了,__len__()方 ...
- Python之路:Python 基础(二)
一.作用域 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. if 1==1: name = 'lenliu' print name 下面的结论对吗?(对) 外层变量,可以被 ...
- Python 基础 四 面向对象杂谈
Python 基础 四 面向对象杂谈 一.isinstance(obj,cls) 与issubcalss(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls ...
- python基础——面向对象进阶下
python基础--面向对象进阶下 1 __setitem__,__getitem,__delitem__ 把对象操作属性模拟成字典的格式 想对比__getattr__(), __setattr__( ...
- python基础语法及知识点总结
本文转载于星过无痕的博客http://www.cnblogs.com/linxiangpeng/p/6403991.html 在此表达对原创作者的感激之情,多谢星过无痕的分享!谢谢! Python学习 ...
- 二十四. Python基础(24)--封装
二十四. Python基础(24)--封装 ● 知识结构 ● 类属性和__slots__属性 class Student(object): grade = 3 # 也可以写在__slots ...
- Python基础复习面向对象篇
目录 类与对象的概念 实例方法 实例变量 初始化方法 析构方法 常用内置方法 继承 类方法与静态方法 动态扩展类与实例 @property装饰器 概述 面向对象是当前流行的程序设计方法,其以人类习惯的 ...
- python基础全部知识点整理,超级全(20万字+)
目录 Python编程语言简介 https://www.cnblogs.com/hany-postq473111315/p/12256134.html Python环境搭建及中文编码 https:// ...
随机推荐
- sqlite 去除换行符
去除换行符操作: update t_config_list ;
- springMVC-1
1.springMVC请求由前端到后端的流程 2.配置过程 (1)需要的jar包 spring-aop.jar spring-beans.jar spring-context.jar spring-c ...
- jQuery插件之simplemodal
1.simplemodal在内部定义了如下css类 simplemodal-overlay:遮罩 simplemodal-container:弹出窗口容器 simplemodal-wrap simpl ...
- 霸气!Nginx 中缓存静态文件秘籍
导读 这篇教程说明你应该怎样配置 nginx.设置 HTTP 头部过期时间,用 Cache-Control 中的 max-age 标记为静态文件(比如图片. CSS 和 Javascript 文件)设 ...
- word20161204
CA, certification authority / 证书颁发机构 cache / 高速缓存 cache file / 缓存文件 caching / 缓存 caching resolver / ...
- Apache Thrift 服务开发框架学习记录
Apache Thrift 是 Facebook 实现的一种高效的.支持多种编程语言的远程服务调用的框架. 前言: 目前流行的服务调用方式有很多种,例如基于 SOAP 消息格式的 Web Servic ...
- json_decode()和json_encode()的使用方法
json_decode对JSON格式的字符串进行编码 json_encode对变量进行 JSON 编码 JS中对JSON的解析 一.JSON字符串转换为JSON对象 要运用上面的str1,必须 ...
- django的views里面的request对象详解大全
简介 HTTP 应用的信息是通过 请求报文 和 响应报文 传递的,关于更多的相关知识,可以阅读<HTTP权威指南>获得. 其中 请求报文 由客户端发送,其中包含和许多的信息,而 djang ...
- dtw算法
dtw路径与线性变换路径对比 转自:http://baike.baidu.com/link?url=z4gFUEplOyqpgboea6My0mZP ...
- poj 2378 (dijkstra)
http://poj.org/problem?id=2387 一个dijkstra的模板题 #include <stdio.h> #include <string.h> #de ...