Friday, September 3, 2010

Programming in python : Classes

Create a class as follows,

>>> class abc():
... a = 1
... b = 2
...
create x as an instance of the class abc,

>>> x = abc()
>>> x
<__main__.abc instance at 0xb7fab3ac>
>>> x.b
2
Create another class with a function definition,

>>> class abc():
... a = 3
... b = 4
... def fun():
... print 'hello'
...
>>> x = abc()
>>> x.a
3
>>> x.b
4
>>> x.fun()
Traceback (most recent call last):
File "", line 1, in
TypeError: fun() takes no arguments (1 given)

We cannot call the function in class abc, as an attribute of x. x has no such an attribute. But the address of x is already given by the interpreter as a parameter to that function. Usually we give an extra parameter 'self', have no special meaning.

>>> class abc():
... a = 1
... b = 2
... def fun(self):
... p = 5
... q = 6
... print 'hello'
...
>>> x = abc()
>>> x.a
>>> 1
>>> x.p
>>> x.fun()
The above statement causes an error. Because x has no attribute p. 'x.fun()' cannot print hello, so little changes are needed to our code and is shown below.

>>> class abc():
... x = 1
... y = 2
... def fun(self):
... self.p = 3
... self.q = 4
... print 'Hello'
...
>>> m = abc()
>>> m.p
Traceback (most recent call last):
File "", line 1, in
AttributeError: abc instance has no attribute 'p'

Here the interpreter says that the abc instance has no attribute 'p'.'p' is an attribute of the function 'fun'. So create an instance of abc and pass the address of m to 'self'.

>>> m = abc()
>>> m .fun()
Hello

No comments:

Post a Comment