In this article, i will get in brief into objects. As usual here are all the articles related to Python:
- Seven steps to compile Python 3.5.0 from source
- Getting started with Python and Anjuta
- Starting up with Python – Part 1 – Numbers and Maths, Variables
- Starting up with Python – Part 2 – Modules and Functions, Strings
- Starting up with Python – Part 3 – Sequences and List, Slicing and Editing
- Starting up with Python – Part 4 – More list functions and Slicing lists
- Starting up with Python – Part 5 – Methods
- Starting up with Python – Part 6 – Sort and Tuples, Strings and stuffs, methods and Dictionary
- Starting up with Python – Part 7 – If statement, Else and elif statements
- Starting up with Python – Part 8 – Nesting and Comparison operators
- Starting up with Python – Part 9 – And and Or operators
- Starting up with Python – Part 10 – While, For, Infinite and Break Loops
- Starting up with Python – Part 11 – Building functions and Default parameters
- Starting up with Python – Part 12 – Multiple Parameters, Parameter Types and Tuples as Parameters
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