File: pramode.html

package info (click to toggle)
lg-issue54 2-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,708 kB
  • ctags: 124
  • sloc: perl: 720; sh: 245; makefile: 34
file content (317 lines) | stat: -rw-r--r-- 10,521 bytes parent folder | download
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
<!--startcut  ==============================================-->
<!-- *** BEGIN HTML header *** -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML><HEAD>
<title>Special Method Attributes in Python LG #54</title>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#0000AF"
ALINK="#FF0000">
<!-- *** END HTML header *** -->

<CENTER>
<A HREF="http://www.linuxgazette.com/">
<H1><IMG ALT="LINUX GAZETTE" SRC="../gx/lglogo.jpg" 
	WIDTH="600" HEIGHT="124" border="0"></H1></A> 

<!-- *** BEGIN navbar *** -->
<IMG ALT="" SRC="../gx/navbar/left.jpg" WIDTH="14" HEIGHT="45" BORDER="0" ALIGN="bottom"><A HREF="okopnik.html"><IMG ALT="[ Prev ]" SRC="../gx/navbar/prev.jpg" WIDTH="16" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="index.html"><IMG ALT="[ Table of Contents ]" SRC="../gx/navbar/toc.jpg" WIDTH="220" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../index.html"><IMG ALT="[ Front Page ]" SRC="../gx/navbar/frontpage.jpg" WIDTH="137" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="http://www.linuxgazette.com/cgi-bin/talkback/all.py?site=LG&article=http://www.linuxgazette.com/issue54/pramode.html"><IMG ALT="[ Talkback ]" SRC="../gx/navbar/talkback.jpg" WIDTH="121" HEIGHT="45" BORDER="0" ALIGN="bottom"  ></A><A HREF="../faq/index.html"><IMG ALT="[ FAQ ]" SRC="./../gx/navbar/faq.jpg"WIDTH="62" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="sevenich.html"><IMG ALT="[ Next ]" SRC="../gx/navbar/next.jpg" WIDTH="15" HEIGHT="45" BORDER="0" ALIGN="bottom"  ></A><IMG ALT="" SRC="../gx/navbar/right.jpg" WIDTH="15" HEIGHT="45" ALIGN="bottom">
<!-- *** END navbar *** -->
<P>
</CENTER>

<!--endcut ============================================================-->

<H4 ALIGN="center">
"Linux Gazette...<I>making Linux just a little more fun!</I>"
</H4>

<P> <HR> <P> 
<!--===================================================================-->

<center>
<H1><font color="maroon">Special Method Attributes in Python</font></H1>
<H4>By <a href="mailto:iclabs@vsnl.com">Pramode C E</a></H4>
</center>
<P> <HR> <P>  

<!-- END header -->




<P>
C++ programmers use 'operator overloading' to apply built-in operators to user defined classes. Thus,
a complex number class may have an addition operator which makes it possible for us to use two
objects of type 'complex' in an arithmetic expression in the same way we use integers or floating
point numbers. The Python programming language provides much of the same functionality in a simple
and elegant manner -  using  special method attributes. This is a quick  
introduction to some of the special methods through code snippets which we wrote while trying
to digest the Python language reference. The code has been tested on Python ver 1.5.1.


<H2> Classes and objects in Python </H2>
<p> Let us look at a simple class definition in Python:

<pre>

class foo:
	def __init__(self, n):
		print 'Constructor called'
		self.n = n
		
	def hello(self):
		print 'Hello world'
		
	def change(self, n):
		print 'Changing self.n'
		self.n = n

f = foo(10)  # create an instance of class foo with a data field 'n' whose value is 10.
print f.n    # prints 10. Python does not support member access control the way C++ does.
f.m = 20     # you can even add new fields!
f.hello()    # prints 'Hello world'
foo.change(f, 40)
print f.n    # prints 40

</pre>

The method __init__ is similar to a 'constructor' in C++. It is a
'special method' which is automatically called when an object is
being created. 

<p>We see that all member functions have a 
parameter called 'self'. Now, when we call f.hello(), we are actually calling a method belonging to
class foo with the object 'f' as the first parameter. This parameter is usually called 'self'. Note
that it can be given any other name, though you are encouraged to name it that way by
convention. It is even possible to call <b>f.hello()</b> as <b>foo.hello(f)</b>. C++ programmers will
find some relation between 'self' and the keyword 'this'(in C++) through which the hidden first
parameter to member function invocations can be accessed.


<H2> The special method __add__ </H2>

Consider the following class definition:
<pre>

class foo:
	def __init__(self, n):
		self.n = n
	def __add__(self, right):
		t = foo(0) 
		t.n = self.n + right.n
		return t
		
</pre>

Now  we create two objects f1 and f2 of type 'foo' and add them up:

<pre>

f1 = foo(10)  # f1.n is 10
f2 = foo(20)  # f2.n is 20
f3 = f1 + f2  
print f3.n    # prints 30

</pre>

What happens when Python executes f1+f2 ? In fact, the interpreter simply calls f1.__add__(f2). So the
'self' in function __add__ refers to f1 and 'right' refers to f2. 


<H2> Another flavor of __add__ </H2>

Let us look at another flavor of the __add__ special method:
<pre>

class foo:
	def __init__(self, n):
		self.n = n
	def __radd__(self, left):
		t = foo(0) 
		t.n = self.n + left.n
		print 'left.n is', left.n
		return t
	
f1 = foo(10)
f2 = foo(20)
f3 = f1 + f2  # prints 'left.n is 10'

</pre>

The difference in this case is that f1+f2 is converted into f2.__radd__(f1).


<H2> How objects print themselves - the __str__ special method </H2>

<pre>

class foo:
	def __init__(self, n1, n2):
		self.n1 = n1
		self.n2 = n2
	
	def __str__(self):
		return 'foo instance:'+'n1='+`self.n1`+','+'n2='+`self.n2`
		
</pre>

class foo defines a special method called __str__. We will see it in action if we run the following
test code:
<pre>

f1 = foo(10,20)
print f1    # prints 'foo instance: n1=10,n2=20'

</pre>

The reader is encouraged to look up the Python Language Reference and see how a similar function,
__repr__ works.


<H2> Truth value testing with __nonzero__ </H2>

<p>
__nonzero__ is called to implement truth value testing. It should return 0 or 1. When this method is not defined,
__len__ is called, if it(__len__) is defined. If a class defines neither __len__ nor __nonzero__, all its
instances are considered true. This is how the language reference defines __nonzero__.

<p> Let us put this to test.

<pre>

class foo:
	def __nonzero__(self):
		return 0
		
class baz:
	def __len__(self):
		return 0
		
class abc:
	pass
	

f1 = foo()
f2 = baz()
f3 = abc()
		
if (not f1): print 'foo: false'  # prints 'foo: false'
if (not f2): print 'baz: false'  # prints 'baz: false'
if (not f3): print 'abc: false'  # does not print anything

</pre>


<H2> The magic of __getitem__ </H2>

How would you like your object to behave like a list? The 
distinguishing feature of a  list (or tuple, or what is in general called a 'sequence' type)
is that it supports indexing. That is, you are able to write things like 'print a[i]'.
There is a special method called __getitem__ which has been designed to support indexing
on user defined objects. Here is an example:

<pre>

class foo:
	def __init__(self, limit):
		self.limit = limit
		
	def __getitem__(self, key):
		if ((key &gt; self.limit-1) or (key &lt; -(self.limit-1))):
			raise IndexError
		else:
			return 2*key
			
f = foo(10)       # f acts like a 20 element array 
print f[0], f[1]  # prints 0, 2
print f[-3]       # prints -6
print f[10]       # generates IndexError

</pre>

There are some additional methods available like __setitem__, __delitem__, __getslice__, __setslice__,
__delslice__ .


<H2> Attribute access with __getattr__</H2>

 __getattr__(self,name) is called when attribute lookup fails to find the attribute
whose name is given as the second argument. It should either raise an AttributeError exception
or return a computed attribute value.

<pre>

class foo:
	def __getattr__(self, name):
		return 'no such attribute'
		
f = foo()
f.n = 100
print f.n     # prints 100
print f.m     # prints 'no such attribute'

</pre>

Note that we also have a builtin function getattr(object, name). Thus, getattr(f, 'n') returns 100
and getattr(f,'m') returns the string 'no such attribute'.

It is easy to implement stuff like delegation using getattr. Here is an example:

<pre>

class Boss:
	def __init__(self, delegate):
		self.d = delegate
		
	def credits(self):
		print 'I am the great boss, I did all that amazing stuff'
		
	def __getattr__(self, name):
		return getattr(self.d, name)
		
	
class Worker:
	def work(self):
		print 'Sigh, I am the worker, and I get to do all the work'
		
	
w = Worker()	
b = Boss(w)
b.credits()  # prints 'I am the great boss, I did all that amazing stuff'
b.work()     # prints 'Sigh, I am the worker, and I get to do all the work'

</pre>


<H2> Further Reading </H2>

The Python distribution comes with excellent documentation, which includes a
tutorial, language reference and library reference. If you are a beginner to
Python, you should start by reading Guido's excellent 
<A HREF="http://www.python.org/doc/current/tut/tut.html">tutorial</A>. Then you
can browse through the 
<A HREF="http://www.python.org/doc/current/ref/ref.html">language reference</A>
and 
<A HREF="http://www.python.org/doc/current/lib/lib.html">library reference</A>.
This article was written with the help of the language reference.




<!-- *** BEGIN copyright *** -->
<P> <hr> <!-- P --> 
<H5 ALIGN=center>

Copyright &copy; 2000, Pramode C E<BR> 
Published in Issue 54 of <i>Linux Gazette</i>, June 2000</H5>
<!-- *** END copyright *** -->

<!--startcut ==========================================================-->
<HR><P>
<CENTER>
<!-- *** BEGIN navbar *** -->
<IMG ALT="" SRC="../gx/navbar/left.jpg" WIDTH="14" HEIGHT="45" BORDER="0" ALIGN="bottom"><A HREF="okopnik.html"><IMG ALT="[ Prev ]" SRC="../gx/navbar/prev.jpg" WIDTH="16" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="index.html"><IMG ALT="[ Table of Contents ]" SRC="../gx/navbar/toc.jpg" WIDTH="220" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../index.html"><IMG ALT="[ Front Page ]" SRC="../gx/navbar/frontpage.jpg" WIDTH="137" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="http://www.linuxgazette.com/cgi-bin/talkback/all.py?site=LG&article=http://www.linuxgazette.com/issue54/pramode.html"><IMG ALT="[ Talkback ]" SRC="../gx/navbar/talkback.jpg" WIDTH="121" HEIGHT="45" BORDER="0" ALIGN="bottom"  ></A><A HREF="../faq/index.html"><IMG ALT="[ FAQ ]" SRC="./../gx/navbar/faq.jpg"WIDTH="62" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="sevenich.html"><IMG ALT="[ Next ]" SRC="../gx/navbar/next.jpg" WIDTH="15" HEIGHT="45" BORDER="0" ALIGN="bottom"  ></A><IMG ALT="" SRC="../gx/navbar/right.jpg" WIDTH="15" HEIGHT="45" ALIGN="bottom">
<!-- *** END navbar *** -->
</CENTER>
</BODY></HTML>
<!--endcut ============================================================-->