使用 __slots__
2016-05-27 17:14
323 查看
动态添加类的属性跟方法:
属性:
class Student(object):
pass
s = Student()
s.name = 'Michael'
print(s.name)
方法:
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
使用 __slots__
class Student(object):
__slots__ = ('name', 'age')
由于
使用
除非在子类中也定义
属性:
class Student(object):
pass
s = Student()
s.name = 'Michael'
print(s.name)
方法:
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
使用 __slots__
class Student(object):
__slots__ = ('name', 'age')
>>> 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__。
相关文章推荐
- 单链表冒泡排序(优化)
- js中数字取整,保留小数位
- Nginx和Tomcat负载均衡实现session共享(转)
- virtualbox复制粘贴文件到虚拟机
- linux中fcntl()、lockf、flock的区别
- sqlite经典书籍及下载地址
- Java学习笔记之异常、处理异常、异常抛出、自定义异常、异常链
- android 进程防止被杀死
- java 常用序列化和反序列化框架使用-json,kyro,jdk
- 偏函数
- 作用域
- iOS 正则表达式(一)
- linux下压缩与解压(zip、unzip、tar)详解
- Android客户端性能优化
- CSS3 过渡、2D变形、3D变形 20160527
- 关于MVC的一点看法
- java中this的用法学习
- 一个操作系统的实现(5)-关于特权级
- 一段有意思的代码
- [VS2015].NET4.0环境下使用.NET2.0程序集,使用sqlite时报异常 出现“混合模式程序集异常”