summaryrefslogtreecommitdiff
path: root/C++_from_the_Ground/Chapter_11(1).ipynb
blob: b59e52c7283f51ef5a7d84107315e279a45f5229 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
{
 "metadata": {
  "name": "Chapter 11"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h1>Chapter 11: Introducing the Class<h1>"
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.1, Page Number: 249<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Illustration of a class in python'''\n\n#This creates the class queue\nclass queue:\n    #Initialize the queue \n    def __init__(self):\n        self.__sloc=0\n        self.__rloc=-1\n        self.__q=[]\n        \n    #Put an integer into the queue\n    def qput(self,i):\n        if self.__sloc==100:\n            print \"Queue is full.\"\n            return\n        self.__sloc+=1\n        self.__q.append(i)\n        \n    #Get an integer from the queue\n    def qget(self):\n        if self.__rloc==self.__sloc:\n            print \"Queue underflow\"\n            return\n        self.__rloc+=1\n        return self.__q[self.__rloc]     \n    \n\n    \n#Create two queue objects\nb=queue()\na=queue()\n\na.qput(10)\nb.qput(19)\n\na.qput(20)\nb.qput(1)\n\n#Result\nprint \"Contents of queue a: \",\nprint a.qget(),' ',a.qget()\n\nprint \"Contents of queue b: \",\nprint b.qget(),' ',b.qget()\n\n\n    \n",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Contents of queue a:  10   20\nContents of queue b:  19   1\n"
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.2, Page Number: 250<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Demonstrate class member access'''\n    \nclass myclass:\n    def __init__(self):\n        self.__a=None  #private member\n        self.b=None    #public member\n    #public functions\n    def setlab(self,i):\n        self.__a=i      #refer to a\n        self.b=i*i    #refer to b\n        return\n    def geta(self):\n        return self.__a #refer to a\n    def reset(self):\n        #call setlab using self\n        self.setlab(0)     #the object is already known\n            \n        \nob=myclass()\nob.setlab(5)      #set ob.a and ob.b\nprint \"ob after setlab(5): \",ob.geta(),' ',\nprint ob.b #can access b because it is public\n\nob.b=20    #can access b because it is public\nprint \"ob after ob.b=20: \",\nprint ob.geta(),' ',ob.b\n\nob.reset()\nprint \"ob after ob.reset(): \",ob.geta(),' ',ob.b\n\n",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "ob after setlab(5):  5   25\nob after ob.b=20:  5   20\nob after ob.reset():  0   0\n"
      }
     ],
     "prompt_number": 4
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.3, Page Number: 254<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Demonstrate a constructor and a destructor'''\n#The destructors of python behave a little differently.\n\n#This creates the class queue\nclass queue:\n    \n    #Constructor\n    def __init__(self):      \n        self.__q=[]\n        self.__rloc=-1\n        self.__sloc=0\n        print \"Queue initialized\"\n        \n    #Destructor\n    def __del__(self):\n        print (\"Queue destroyed\")\n        \n    #Put an integer into the queue\n    def qput(self,i):\n        if self.__sloc == 100:\n            print \"Queue is full\"\n            return \n        self.__sloc+=1\n        self.__q.append(i)\n        \n    #Get an integer from the queue\n    def qget(self):\n        if self.__rloc==self.__sloc:\n            print \"Queue underflow\"\n            return\n        self.__rloc+=1\n        return self.__q[self.__rloc]\n        \n#Create two queue objects\na=queue()\n\n\na.qput(10)\na.qput(20)\nb=queue()\nb.qput(19)\n\nb.qput(1)\n\n#Result\nprint a.qget(),' ',\nprint a.qget(),' ',\nprint b.qget(),' ',\nprint b.qget(),' '\n",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Queue initialized\nQueue destroyed\nQueue initialized\nQueue destroyed\n10   20   19   1  \n"
      }
     ],
     "prompt_number": 2
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.4, Page Number: 257<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Parameterized Constructors'''\n\n#This creates the class queue\nclass queue:                            \n    \n    #Constructor\n    def __init__(self,i):      \n        self.__q=[]\n        self.__rloc=-1\n        self.__sloc=0\n        self.__who=i\n        print \"Queue \",self.__who,\" initialized.\"\n        \n    #Destructor\n    def __del__():\n        print \"Queue \",self.__who,\" destroyed\"\n        \n    #Put an integer into the queue\n    def qput(self,i):\n        if self.__sloc == 100:\n            print \"Queue is full\"\n            return \n        self.__sloc+=1\n        self.__q.append(i)\n        \n    #Get an integer from the queue\n    def qget(self):\n        if self.__rloc==self.__sloc:\n            print \"Queue underflow\"\n            return\n        self.__rloc+=1\n        return self.__q[self.__rloc]\n        \na=queue(1)\nb=queue(2)\n\na.qput(10)\nb.qput(19)\n\na.qput(20)\nb.qput(1)\n\n#Result\nprint a.qget(),' ',\nprint a.qget(),' ',\nprint b.qget(),' ',\nprint b.qget(),' '\n",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Queue  1  initialized.\nQueue destroyed\nQueue  2  initialized.\nQueue destroyed\n10   20   19   1  \n"
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.5, Page Number: 258<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Passing more than a single arguments'''\nclass widget:\n    \n    #Pass two arguments to the constructor\n    def __init__(self,a,b):\n        self.__i=a\n        self.__j=b\n        \n    def put_widget(self):\n        print self.__i,\" \",self.__j\n\n#Initializing\nx=widget(10,20)\ny=widget(0,0)\n\nx.put_widget()\ny.put_widget()\n\n    ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "10   20\n0   0\n"
      }
     ],
     "prompt_number": 5
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.6, Page Number: 259<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''An example of class'''\n\nclass myclass:\n    \n    #Constructor\n    def __init__(self,x):\n        self.a=x\n    #To get the vale of a\n    def get_a(self):\n        return self.a\n\n#Initializing\nob=myclass(4)\n\n#Result\nprint ob.get_a()",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "4\n"
      }
     ],
     "prompt_number": 1
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.7, Page Number: 260<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Using structures to create a class'''\n\nfrom ctypes import *\n\nclass c1(Structure):\n    _fields_=[(\"__i\", c_int)]  #private member\n    def get_i(self):           #public finctions\n        return self.__i\n    def put_i(self,j):\n        self.__i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()\n        \n    ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "10\n"
      }
     ],
     "prompt_number": 1
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.8, Page Number: 261<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Now we use class instead'''\n\nclass c1:\n    def __init__(self):\n        self.__i=None   #private member\n    def get_i(self):    #public finctions\n        return self.__i\n    def put_i(self,j):\n        self.__i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()\n        \n    ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "10\n"
      }
     ],
     "prompt_number": 2
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.9, Page Number: 263<h3> "
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Create a union-based class'''\n\nfrom ctypes import *\n\n#Creates a union\nclass u_type(Union):\n    _fields_ = [(\"i\",c_short),\n            (\"ch\", c_char*2)]\n    #Constructor\n    def __init__(self,a):\n        self.i=a\n        \n    #Show the characters that comprise a short int.\n    def showchars(self):\n        print self.ch[0]\n        print self.ch[1]\n        \n        \nu=u_type(1000)\n\n#Displays char of 1000\nu.showchars()",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "\ufffd\n\u0003\n"
      }
     ],
     "prompt_number": 2
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.10, Page Number: 264<h3> "
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''A simple class program'''\n#There is no inline function in python\n\nclass c1:\n    def __init__(self):\n        self.__i=None\n    def get_i(self):\n        return self.i\n    def put_i(self,j):\n        self.i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "10\n"
      }
     ],
     "prompt_number": 2
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.11, Page Number: 265<h3> "
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''A simple class program'''\n#There is no inline functions in python\n\nclass c1:\n    def __init__(self):\n        self.__i=None\n    def get_i(self):\n        return self.i\n    def put_i(self,j):\n        self.i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "10\n"
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.12, Page Number: 267<h3> "
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''An example of arrays of objects'''\n\nclass display:\n    def __init__(self):\n        width=None\n        height=None\n        res=None\n    def set_dim(self,w,h):\n        self.width=w\n        self.height=h\n    def get_dim(self):\n        return self.width,self.height\n    def set_res(self,r):\n        self.res=r\n    def get_res(self):\n        return self.res\n        \n#Variable decleration\nnames=[\"low\",\"medium\",\"high\"]   \n(low,medium,high)=(0,1,2)    #For enumeration type\nw=None\nh=None\ndisplay_mode=[]*3\n\nfor i in range(3):\n    display_mode.append(display())\n\n#Initialize the array of objects using member functions\ndisplay_mode[0].set_res(low)\ndisplay_mode[0].set_dim(640,480)\n\ndisplay_mode[1].set_res(medium)\ndisplay_mode[1].set_dim(800,600)\n\ndisplay_mode[2].set_res(high)\ndisplay_mode[2].set_dim(1600,1200)\n\n#Result\nprint \"Available display modes: \"\nfor i in range(3):\n    print names[display_mode[i].get_res()],\" : \",\n    w,h=display_mode[i].get_dim()\n    print w,\" by \",h",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Available display modes: \nlow  :  640  by  480\nmedium  :  800  by  600\nhigh  :  1600  by  1200\n"
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.13, Page Number: 268<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Initialize an array of objects'''\n\nclass samp:\n    __a=None\n    def __init__(self,n):\n        self.__a=n\n    def get_a(self):\n        return self.__a\n\n#Initializing the list\nsampArray=[samp(-1),samp(-2),samp(-3),samp(-4)]\n\n#Display\nfor i in range(4):\n    print sampArray[i].get_a(),' ',",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "-1   -2   -3   -4  \n"
      }
     ],
     "prompt_number": 4
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.14, Page Number: 269<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Two dimensional array if objects'''\n\nclass samp:\n    __a=None\n    __b=None\n    def __init__(self,n,m):\n        self.__a=n\n        self.__b=m\n    def get_a(self):\n        return self.__a\n    def get_b(self):\n        return self.__b\n \n#Initializing the list\nsampArray=[[samp(1,2),samp(3,4)],\n           [samp(5,6),samp(7,8)],\n           [samp(9,10),samp(11,12)],\n           [samp(13,14),samp(15,16)]]\n\n#Display\nfor i in range(4):\n    print sampArray[i][0].get_a(),' ',\n    print sampArray[i][0].get_b()\n    print sampArray[i][1].get_a(),' ',\n    print sampArray[i][1].get_b()",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "1   2\n3   4\n5   6\n7   8\n9   10\n11   12\n13   14\n15   16\n"
      }
     ],
     "prompt_number": 5
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.15, Page Number: 270<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''A simple example using an object pointer'''\n\nfrom ctypes import *\n\nclass P_example(Structure):\n    __num=None\n    def set_num(self,val):\n        self.__num=val\n    def show_num(self):\n        print self.__num\n\n#Variable declaration\nob=P_example()          #Declare an object to the structure\np=POINTER(P_example)    #Declare a pointer to the structure\n\nob.set_num(1)           #access ob directly\nob.show_num()\n\np=ob                    #assign p the address of ob\np.show_num()            #access ob using pointer\n        \n        ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "1\n1\n"
      }
     ],
     "prompt_number": 6
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 11.16, Page Number: 271<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Pointer to array of objects'''\n\nclass P_example(Structure):\n    __num=None\n    def set_num(self,val):\n        self.__num=val\n    def show_num(self):\n        print self.__num\n        \n#Variable declaration\nob=[P_example(),P_example()]          #Declare an object to the structure\np=POINTER(P_example)                  #Declare a pointer to the structure\n\nob[0].set_num(10)                     #access objects directly\nob[1].set_num(20)\n\np=ob                             #obtain pointer to first element\np[0].show_num()                  #access ob using pointer\n\np[1].show_num()\n\np[0].show_num()\n",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "10\n20\n10\n"
      }
     ],
     "prompt_number": 7
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "",
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}