Starting up with Python – Part13

In this article, i will get in brief into objects. As usual here are all the articles related to Python:

python_logo_by_bluex_pl

30. Object Oriented Program

An object contains data and also has methods. A method in an Object is just like a function and it is called when it is inside an Object and it will use data from the very same object. An example of using a method in an object can be Mauritius.hacks() However, before building objects, classes need to be build. Let's build a class.

>> class hackersClass:
 ... country="mauritius"
 ... members=8
 ... def thisMethod(self):
 ... return 'This method worked'
 ...
 >>> hackersClass
 <class __main__.hackersClass at 0xb721e32c>

A class has been build and it even shows us that it works. Let's now make an object. I need the object to get the data from the class. We start by making an object set equal to the class.

>> hackersObject=hackersClass()
 >>> hackersObject.country
 'mauritius'
 >>> hackersObject.members
 8
>> hackersObject.thisMethod()
 'This method worked'

So many objects can be build to refer to the same class. Cool isn't it?

31. Classes and Self

The keyword class will be needed. This is a like a blueprint which is made to create methods and the "self" is made as we do not now the object name

>> class classname:
... def createName(self,name):
... self.name=name
... def displayName(self):
... return self.name
... def saying(self):
... print "hello %s" % self.name
... 
>>> classname
<class __main__.classname at 0xb722d32c>
>>> first=className()

Lets now use the objects. Now it take self and replace it with the object name.

first=classname()
>>> second=classname()
>>> first.createName('nitin')
>>> second.createName('test')
>>> first.displayName()
'nitin'
>>> first.saying() 
hello nitin