যারা বাংলাদেশের ৩৬ তম Zend Certified Engineer এবং এই সাইট (w3programmers) এর স্বত্বাধিকারী এবং লেখক Masud Alam স্যার এর কাছে কাছে সপ্তাহে ২ দিন ক্লাস, ৬ দিন প্রাকটিস করতে চান তাদের জন্য আগামী ১ February 2018 (বৃহস্পতি এবং শুক্রবার সন্ধ্যা ৬:০০ টা রাত ৯:০০ টা) থেকে শুরু হতে যাচ্ছে ৫ মাস ব্যাপী Professional Web Design & Development With HTML, CSS, JAVASCRIPT, JQUERY, PHP & MySQL for Beginners কোর্স (এই কোর্স টি যারা ফ্রিল্যান্সিং এবং আউটসোর্সিং কাজে আগ্রহী বিশেষ ভাবে তাদের জন্য design করা হয়েছে। ), আগামী ৪ February 2018 ( রবি এবং মঙ্গলবার সন্ধ্যা ৬:০০ টা থেকে রাত ৯:০০ টা ) থেকে শুরু হতে যাচ্ছে ৪ মাস ব্যাপী Zend Certified PHP 7.1 Engineering কোর্স। যেটা Advance PHP কোর্স নামে পরিচিত । এবং ৫ February 2018 (সোম এবং বুধবার সন্ধ্যা ৬:০০ টা থেকে রাত ৯:০০ টা) থেকে শুরু হতে যাচ্ছে ৪ মাস ব্যাপী Laravel 5.5 Professional Beginning to Advance Course কোর্স ।এই কোর্স গুলোতে তিনি ছাত্রদের কে সপ্তাহে ২ দিন ৩ ঘন্টা করে ৬ ঘন্টা ক্লাস নিবেন , এবং শনি থেকে বৃহস্পতি সপ্তাহে ৬ দিন ই স্যার এর অফিসে বসে প্রাকটিস করার সুযোগ দিবেন ! এতে প্রাকটিস করা কালীন ছাত্র-ছাত্রীরা কোনো সমস্যায় পড়লে তাৎক্ষণিক স্যার এর সহযোগিতা পাবে . (উল্লেখ্য: Training গুলো স্যার তার techbeeo software company'r পাশাপাশি পরিচালনা করে থাকেন।) কোর্স গুলো সম্পর্কে বিস্তারিত জানতে পারবেন এই লিংকে : Course Details .কোর্স গুলোর প্রত্যেকটির ফী নির্ধারণ করা হয়েছে ৩০,০০০ টাকা। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

OOP with Python

By born, Python supports Object Oriented Programming (OOP). We will learn in detail the Python OOP features. Before that we will learn some important topics, which will empower our knowledge of Python programming.

python2

Topics:
In this tutorial we are going to learn the following topics –

1. Comments
2. Modules
3. Assessing Files
4. Encapsulating Data
5. Inheritance
6. Overriding
7. Polymorphism

1. Comments
There are two kinds of comments in Python. First one is single line comment and the second one is multiline comment. The second one also called docstring in Python.

# this is the first comment

“”” This is
multi line 
comment”””

The docstring specially stated right after declaring module, function, class, or method.

Like –

def printMe():
	“”” this function will print 0 to 4 “””
	for i in range(0, 5):
		print i

printMe()

All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

The fun is you can see the docstring from Python shell like –

>>> print printMe.__doc__

2. Modules
Modules are simple Python script, which accomplish some task. It helps programmers at the time of coding by doing some job. Usually Python modules can be imported. We can import whole module or specific function of that module to make our job done.

Let’s create a simple Python script called “fibonacci.py” and write the following lines of code:

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b

def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

This script contains two functions, fib() and fib2(). So for our purpose we can import the whole module or a particular one or two function of the module, as needed.

So, let’s create one more Python script, say – fibcall.py

from fibonacci import fib


fib(10)

Now change the same script as follows:

from fibonacci import fib2


print fib2(10)

Or, as follows:

from fibonacci import *

fib(10)
print ""
print fib2(10)

We can find thousand of modules in PyPI, https://pypi.python.org/pypi. PyPI is called Python Package Index. Like, PyMySQL is for MySQL driver and Django is a popular web framework.

To install just run the following commands from your console:

$ pip install PyMySQL
$ pip install django

These commands will download and install all the dependencies and install into your environment.

You can check you’re these installed modules from your Python console.

>>> import pymysql
>>> pymysql.get_client_info()
'0.6.6.None'

>>> import django
>>> django.get_version()
'1.8.2'

3. Assessing Files
In Python, creating, reading and writing in the file is very easy. The file object has different methods for working with files, open(), read(), write() and close(). The open() function takes two arguments, one is one is file name and other is file mode. The file has several “mode” of opening. Like-

r: Open and existing file to read.
w: Open an existing file to write. Creates a new file if none exists or opens an existing file and discards all its previous contents.
a: Append text. Opens or creates a text file for writing at the end of the file.
r+: Open a text file to read from or write.
w+: Open a text file to write to or read from.
a+: Open or creates a text file to read from or write to at the end of the file.

Now create a python script called fileaccess.py in our directory.

# creating a file for writing
file = open("example.txt", "w")

file.write("This is my first text for the file.")

file.close()

# opening the file for reading
file = open("example.txt", "r")

content = file.readline()

file.close()

print content

As simple as it is right!!!

4. Encapsulating Data
Encapsulating data means we will enclose all the varialbes and methods inside a class. The basic structure of Python class structure is using “class” keyword and name the class name. Usually, the class name and the file name is same, it is a good practice. The basic structure of a simple class is given below. Let’s create a Python class file called Bird.py –

class Bird :

	'''A base class to define bird properties.'''

	count = 0

	def __init__( self , chat ) :

		self.sound = chat
		Bird.count += 1

	def talk( self ) :

		return self.sound

The bird class contains two methods __init__() and talk().

__init__() is called class constructor or initialization method that Python calls when you create a new instance of this class.

talk() is a regular method.

Now let’s create one more python file called Encapsul.py and don’t forget to import Bird class.

from Bird import *

print( '\nClass Instances Of:\n' , Bird.__doc__ )

polly = Bird( 'Squawk, squawk!' )

print( '\nNumber Of Birds:' , polly.count )
print( 'Polly Says:' , polly.talk() )

harry = Bird( 'Tweet, tweet!' )
print( '\nNumber Of Birds:' , harry.count )
print( 'Harry Says:' , harry.talk() )

5. Inheritance
The concept of inheritance in OOP is same for all the languages. The class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.

To understand inheritance let’s create on Python class called Polygon.py

class Polygon :
	width = 0
	height = 0
	def set_values( self , width , height ) :
		Polygon.width = width
		Polygon.height = height

Then import it form another class, Rectangle.py

from Polygon import *

class Rectangle( Polygon ) :
	def area( self ) :
		return self.width * self.height

Now, create one more class, Triangle.py

from Polygon import *

class Triangle( Polygon ) :
	def area( self ) :
		return ( self.width * self.height ) / 2

If you check it carefully, Rectangle and Triangle class contains one same method called area. However the definition is different. First one calculates the area of rectangle and the next one calculate the area of triangle.

To test it, create one more Python file called, inherit.py and import the both class.

from Rectangle import *
from Triangle import *

rect = Rectangle()
trey = Triangle()

rect.set_values( 4 , 5 )
trey.set_values( 4 , 5 )

print( 'Rectangle Area:' , rect.area() )
print( 'Triangle Area:' , trey.area() )

6. Overriding
Data attributes override method attributes with the same name; to avoid accidental name conflicts, which may cause hard-to-find bugs in large programs, it is wise to use some kind of convention that minimizes the chance of conflicts. Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.

So, to test the overriding mechanism let’s create three classes one by one called, Person.py the base class, Man.py and Woman.py contains overridden method called speak.

class Person :

	'''A base class to define Person properties.'''

	def __init__( self , name ) : 
		self.name = name

	def speak( self , msg  = '(Calling The Base Class)' ) :
		print( self.name , msg )

from Person import *

'''A derived class to define Man properties.'''

class Man( Person ) :

	def speak( self , msg ) :
		print( self.name , ':\n\tHello!' , msg )

from Person import *

'''A derived class to define Hombre properties.'''

class Woman( Person ) :
	def speak( self , msg ) :
		print( self.name , ':\n\tHi!' , msg )

Now create one python file called override.py to check our overriding mechanism.

from Man import *
from Woman import *

guy_1 = Man( 'Richard' )
guy_2 = Woman ( 'Anne ' )

guy_1.speak( 'It\'s a beautiful evening, from Richard.\n' )
guy_2.speak('It\'s a beautiful evening, from Anne.\n')

Person.speak( guy_1 )
Person.speak( guy_2 )

7. Polymorphism
In programming languages, polymorphism (from Greek, polys, “many, much” and, morphē, “form, shape”) means many form of a single intrface.

Let’s check it by example, create two classes Duck.py and Mouse.py. Both the class contains talk() and coat() methods.

class Duck :

	'''A class to define Duck properties.'''

	def talk( self ) :
		print( '\nDuck Says: Quack!' )

	def coat( self ) :
		print( 'Duck Wears: Feathers' )

class Mouse :

	'''A class to define Mouse properties.'''

	def talk( self ) :
		print( '\nMouse Says: Squeak!' )

	def coat( self ) :
		print( 'Mouse Wears: Fur' )

Now create polymorph.py, which imports Duck and Mouse class and all the properties.

from Duck import *
from Mouse import *
 
def describe( object ) :
	object.talk()
	object.coat()

donald = Duck()
mickey = Mouse()

describe( donald )
describe( mickey )

We are all done with Object Oriented Programming features of Python. However, Python does not support the technique of “overloading” found in other languages – in which methods of the same name can be created with different argument lists in a single class.

You can download all the codes from my github account.

Happy coding… 🙂

OOP with Python

Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.

Leave a Reply

Your email address will not be published. Required fields are marked *