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:


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.members
>> 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):
... def displayName(self):
... return
... def saying(self):
... print "hello %s" %
>>> classname
<class __main__.classname at 0xb722d32c>
>>> first=className()

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

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