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

2018-06-17 23:55:42来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

一、动态添加属性

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'

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python自动化--语言基础3--字典、函数、全局/局部变量

下一篇:Python_基础_01