码迷,mamicode.com
首页 > 编程语言 > 详细

python 面向对象六 动态添加方法 __slots__限制动态添加方法

时间:2017-12-17 20:43:00      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:名称   core   object   允许   class   tuple   ...   method   tee   

一、动态添加属性

1 >>> class Student(object):
2     pass
3 
4 >>> st = Student()
5 >>> st.name = Jack
6 >>> st.name
7 Jack

二、动态给实例添加方法

 1 >>> from types import MethodType
 2 >>> class Student(object):
 3     pass
 4 
 5 >>> def set_age(self, age):
 6     self.age = age
 7     
 8 >>> st.set_age = MethodType(set_age, st)   # 给实例绑定一个方法
 9 >>> st.set_age(25)
10 >>> st.age
11 25

三、动态给类添加方法

 1 >>> class Student(object):
 2     pass
 3 
 4 >>> def set_score(self, score):
 5     self.score = score
 6 
 7 >>> Student.set_score = set_score
 8 >>> s1 = Student()
 9 >>> s1.set_score(100)
10 >>> s1.score
11 100
12 >>> s2 = Student()
13 >>> s2.set_score(50)
14 >>> s2.score
15 50

四、限制实例的属性 __slots__

 1 >>> class Student(object):
 2     __slots__ = (name, age)   # 用tuple定义允许绑定对的属性名称
 3     
 4 >>> s = Student()
 5 >>> s.name = Jack
 6 >>> s.age = 20
 7 >>> s.score = 100
 8 Traceback (most recent call last):
 9   File "<pyshell#53>", line 1, in <module>
10     s.score = 100
11 AttributeError: Student object has no attribute score

__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:

1 >>> class GraduateStudent(Student):
2 ...     pass
3 ...
4 >>> g = GraduateStudent()
5 >>> g.score = 9999

除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__:

 1 >>> class GraduateStudent(Student):
 2     __slots__ = (score, )
 3 
 4 >>> g = GraduateStudent()
 5 >>> g.score = 100
 6 >>> g.name = Mike
 7 >>> g.age = 10
 8 >>> g.other = abc
 9 Traceback (most recent call last):
10   File "<pyshell#69>", line 1, in <module>
11     g.other = abc
12 AttributeError: GraduateStudent object has no attribute other

 

python 面向对象六 动态添加方法 __slots__限制动态添加方法

标签:名称   core   object   允许   class   tuple   ...   method   tee   

原文地址:http://www.cnblogs.com/gundan/p/8052884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!