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:// ...
随机推荐
- 第11天 Stack Queue
1.Stack package algs4; import java.util.Iterator; import java.util.NoSuchElementException; public cl ...
- Apache开发模块
输入perl Configure.pl 安装目录...\apache2.2 “httpd.exe” 生成apxs命令, apache2.2下build目录中的config_vars.mk文件 将CC ...
- HDU 5228
#include<stdio.h> #include<string.h> *]; int main(){ int t; scanf("%d",&t) ...
- HDU 4791 Alice's Print Service(2013长沙区域赛现场赛A题)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4791 解题报告:打印店提供打印纸张服务,需要收取费用,输入格式是s1 p1 s2 p2 s3 p3.. ...
- iOS开发——UI进阶篇(十二)事件处理,触摸事件,UITouch,UIEvent,响应者链条,手势识别
触摸事件 在用户使用app过程中,会产生各种各样的事件 一.iOS中的事件可以分为3大类型 触摸事件加速计事件远程控制事件 响应者对象在iOS中不是任何对象都能处理事件,只有继承了UIResponde ...
- mysql 按距离今日时间最近排序
xxx order by abs(DATEDIFF(time_start,now()))
- 分析Masonry
一. 继承关系 1.MASConstraint (abstract) MASViewContraint MASComposisionConstraint 2. UIView NSLayoutConst ...
- Implement a TextView with an animation in its left side
In my case, I want to write a TextView with an animation in its left side. ImageView + TextView coul ...
- svn: E155004 'XX' is already locked
Error:svn: E155004: Run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)svn: E155 ...
- Struts2获取Session方法
Struts2里面有三种方法可以获取request,最好使用ServletRequestAware接口通过IOC机制注入Request对象. 方法1:IOC方式action类实现SessionAwar ...