Classes and objects are the two main aspects of object oriented programming. A class creates a new type where objects are instances of the class. Even integers are treated as objects (of the
int
class)Objects can store data using ordinary variables that belong to the object. Variables that belong to an object or class are called as fields. Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class. This terminology is important because it helps us to differentiate between functions and variables which are separate by itself and those which belong to a class or object. Collectively, the fields and methods can be referred to as the attributes of that class.
Fields are of two types - they can belong to each instance/object of the class or they can belong to the class itself. They are called instance variables and class variables respectively.
A class is created using the class
keyword. The fields and methods of the class are listed in an indented block.
Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self
.
Although, you can give any name for this parameter, it is strongly recommended that you use the name self
- any other name is definitely frowned upon.
... pass
...
>>> p=person()
>>> print p
<__main__.person instance at 0xb776586c>
We have already discussed that classes/objects can have methods just likeThere are many method names which have special significance in Python classes.
functions except that we have an extraself
variable. We will now see
an example.
>>> class person:
... def sayHi(self):
... print "Hai,friend"
...
>>> p=person()
>>> p.sayHi()
Hai,friend
>>>
The __init__ method
The __init__
method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double underscore both in the beginning and at the end in the name.
... def __init__(self,name):
... self.name=name
... def sayHi(self):
... print "Hai, my name is",self.name
...
>>> p=person('amala')
>>> p.sayHi()
Hai, my name is amala
Here, we define the
__init__
method as taking a parameter name
(along with the usual self
). Here, we just create a new field also called name
. Notice these are two different variables even though they have the same name. The dotted notation allows us to differentiate between them. Most importantly, notice that we do not explicitly call the __init__
method but pass the arguments in the parentheses following the class name when creating a new instance of the class. This is the special significance of this method.
No comments:
Post a Comment