Quick Guide

Object Oriented Python – Quick Guide ”; Previous Next Object Oriented Python – Introduction Programming languages are emerging constantly, and so are different methodologies.Object-oriented programming is one such methodology that has become quite popular over past few years. This chapter talks about the features of Python programming language that makes it an object-oriented programming language. Language Programming Classification Scheme Python can be characterized under object-oriented programming methodologies. The following image shows the characteristics of various programming languages. Observe the features of Python that makes it object-oriented. Langauage Classes Categories Langauages Programming Paradigm Procedural C, C++, C#, Objective-C, java, Go Scripting CoffeeScript, JavaScript, Python, Perl, Php, Ruby Functional Clojure, Eralang, Haskell, Scala Compilation Class Static C, C++, C#, Objective-C, java, Go, Haskell, Scala Dynamic CoffeeScript, JavaScript, Python, Perl, Php, Ruby, Clojure, Erlang Type Class Strong C#, java, Go, Python, Ruby, Clojure, Erlang, Haskell, Scala Weak C, C++, C#, Objective-C, CoffeeScript, JavaScript, Perl, Php Memory Class Managed Others Unmanaged C, C++, C#, Objective-C What is Object Oriented Programming? Object Oriented means directed towards objects. In other words, it means functionally directed towards modelling objects. This is one of the many techniques used for modelling complex systems by describing a collection of interacting objects via their data and behavior. Python, an Object Oriented programming (OOP), is a way of programming that focuses on using objects and classes to design and build applications.. Major pillars of Object Oriented Programming (OOP) are Inheritance, Polymorphism, Abstraction, ad Encapsulation. Object Oriented Analysis(OOA) is the process of examining a problem, system or task and identifying the objects and interactions between them. Why to Choose Object Oriented Programming? Python was designed with an object-oriented approach. OOP offers the following advantages − Provides a clear program structure, which makes it easy to map real world problems and their solutions. Facilitates easy maintenance and modification of existing code. Enhances program modularity because each object exists independently and new features can be added easily without disturbing the existing ones. Presents a good framework for code libraries where supplied components can be easily adapted and modified by the programmer. Imparts code reusability Procedural vs. Object Oriented Programming Procedural based programming is derived from structural programming based on the concepts of functions/procedure/routines. It is easy to access and change the data in procedural oriented programming. On the other hand, Object Oriented Programming (OOP) allows decomposition of a problem into a number of units called objects and then build the data and functions around these objects. It emphasis more on the data than procedure or functions. Also in OOP, data is hidden and cannot be accessed by external procedure. The table in the following image shows the major differences between POP and OOP approach. Difference between Procedural Oriented Programming(POP)vs. Object Oriented Programming(OOP). Procedural Oriented Programming ObjectOriented Programming Based On In Pop,entire focus is on data and functions Oops is based on a real world scenario.Whole program is divided into small parts called object Reusability Limited Code reuse Code reuse Approach Top down Approach Object focused Design Access specifiers Not any Public, private and Protected Data movement Data can move freely from functions to function in the system In Oops, data can move and communicate with each other through member functions Data Access In pop, most functions uses global data for sharing that can be accessed freely from function to function in the system In Oops,data cannot move freely from method to method,it can be kept in public or private so we can control the access of data Data Hiding In pop, so specific way to hide data, so little bit less secure It provides data hiding, so much more secure Overloading Not possible Functions and Operator Overloading Example-Languages C, VB, Fortran, Pascal C++, Python, Java, C# Abstraction Uses abstraction at procedure level Uses abstraction at class and object Level Principles of Object Oriented Programming Object Oriented Programming (OOP) is based on the concept of objects rather than actions, and data rather than logic. In order for a programming language to be object-oriented, it should have a mechanism to enable working with classes and objects as well as the implementation and usage of the fundamental object-oriented principles and concepts namely inheritance, abstraction, encapsulation and polymorphism. Let us understand each of the pillars of object-oriented programming in brief − Encapsulation This property hides unnecessary details and makes it easier to manage the program structure. Each object’s implementation and state are hidden behind well-defined boundaries and that provides a clean and simple interface for working with them. One way to accomplish this is by making the data private. Inheritance Inheritance, also called generalization, allows us to capture a hierarchal relationship between classes and objects. For instance, a ‘fruit’ is a generalization of ‘orange’. Inheritance is very useful from a code reuse perspective. Abstraction This property allows us to hide the details and expose only the essential features of a concept or object. For example, a person driving a scooter knows that on pressing a horn, sound is emitted, but he has no idea about how the sound is actually generated on pressing the horn. Polymorphism Poly-morphism means many forms. That is, a thing or action is present in different forms or ways. One good example of polymorphism is constructor overloading in classes. Object-Oriented Python The heart of Python programming is object and OOP, however you need not restrict yourself to use the OOP by organizing your code into classes. OOP adds to the whole design philosophy of Python and encourages a clean and pragmatic way to programming. OOP also enables in writing bigger and complex programs. Modules vs. Classes and Objects Modules are like “Dictionaries” When working on Modules, note the following points − A Python module is a package to encapsulate reusable code. Modules reside in a folder with a __init__.py file on it. Modules contain functions and classes. Modules are imported using the import keyword. Recall that a dictionary is a key-value pair. That means if you have a dictionary with a

Files and Strings

Object Oriented Python – Files and Strings ”; Previous Next Strings Strings are the most popular data types used in every programming language. Why? Because we, understand text better than numbers, so in writing and talking we use text and words, similarly in programming too we use strings. In string we parse text, analyse text semantics, and do data mining – and all this data is human consumed text.The string in Python is immutable. String Manipulation In Python, string can be marked in multiple ways, using single quote ( ‘ ), double quote( “ ) or even triple quote ( ‘’’ ) in case of multiline strings. >>> # String Examples >>> a = “hello” >>> b = ””” A Multi line string, Simple!””” >>> e = (”Multiple” ”strings” ”togethers”) String manipulation is very useful and very widely used in every language. Often, programmers are required to break down strings and examine them closely. Strings can be iterated over (character by character), sliced, or concatenated. The syntax is the same as for lists. The str class has numerous methods on it to make manipulating strings easier. The dir and help commands provides guidance in the Python interpreter how to use them. Below are some of the commonly used string methods we use. Sr.No. Method & Description 1 isalpha() Checks if all characters are Alphabets 2 isdigit() Checks Digit Characters 3 isdecimal() Checks decimal Characters 4 isnumeric() checks Numeric Characters 5 find() Returns the Highest Index of substrings 6 istitle() Checks for Titlecased strings 7 join() Returns a concatenated string 8 lower() returns lower cased string 9 upper() returns upper cased string 10 partion() Returns a tuple 11 bytearray() Returns array of given byte size 12 enumerate() Returns an enumerate object 13 isprintable() Checks printable character Let’s try to run couple of string methods, >>> str1 = ”Hello World!” >>> str1.startswith(”h”) False >>> str1.startswith(”H”) True >>> str1.endswith(”d”) False >>> str1.endswith(”d!”) True >>> str1.find(”o”) 4 >>> #Above returns the index of the first occurence of the character/substring. >>> str1.find(”lo”) 3 >>> str1.upper() ”HELLO WORLD!” >>> str1.lower() ”hello world!” >>> str1.index(”b”) Traceback (most recent call last): File “<pyshell#19>”, line 1, in <module> str1.index(”b”) ValueError: substring not found >>> s = (”hello How Are You”) >>> s.split(” ”) [”hello”, ”How”, ”Are”, ”You”] >>> s1 = s.split(” ”) >>> ”*”.join(s1) ”hello*How*Are*You” >>> s.partition(” ”) (”hello”, ” ”, ”How Are You”) >>> String Formatting In Python 3.x formatting of strings has changed, now it more logical and is more flexible. Formatting can be done using the format() method or the % sign(old style) in format string. The string can contain literal text or replacement fields delimited by braces {} and each replacement field may contains either the numeric index of a positional argument or the name of a keyword argument. syntax str.format(*args, **kwargs) Basic Formatting >>> ”{} {}”.format(”Example”, ”One”) ”Example One” >>> ”{} {}”.format(”pie”, ”3.1415926”) ”pie 3.1415926” Below example allows re-arrange the order of display without changing the arguments. >>> ”{1} {0}”.format(”pie”, ”3.1415926”) ”3.1415926 pie” Padding and aligning strings A value can be padded to a specific length. >>> #Padding Character, can be space or special character >>> ”{:12}”.format(”PYTHON”) ”PYTHON ” >>> ”{:>12}”.format(”PYTHON”) ” PYTHON” >>> ”{:<{}s}”.format(”PYTHON”,12) ”PYTHON ” >>> ”{:*<12}”.format(”PYTHON”) ”PYTHON******” >>> ”{:*^12}”.format(”PYTHON”) ”***PYTHON***” >>> ”{:.15}”.format(”PYTHON OBJECT ORIENTED PROGRAMMING”) ”PYTHON OBJECT O” >>> #Above, truncated 15 characters from the left side of a specified string >>> ”{:.{}}”.format(”PYTHON OBJECT ORIENTED”,15) ”PYTHON OBJECT O” >>> #Named Placeholders >>> data = {”Name”:”Raghu”, ”Place”:”Bangalore”} >>> ”{Name} {Place}”.format(**data) ”Raghu Bangalore” >>> #Datetime >>> from datetime import datetime >>> ”{:%Y/%m/%d.%H:%M}”.format(datetime(2018,3,26,9,57)) ”2018/03/26.09:57” Strings are Unicode Strings as collections of immutable Unicode characters. Unicode strings provide an opportunity to create software or programs that works everywhere because the Unicode strings can represent any possible character not just the ASCII characters. Many IO operations only know how to deal with bytes, even if the bytes object refers to textual data. It is therefore very important to know how to interchange between bytes and Unicode. Converting text to bytes Converting a strings to byte object is termed as encoding. There are numerous forms of encoding, most common ones are: PNG; JPEG, MP3, WAV, ASCII, UTF-8 etc. Also this(encoding) is a format to represent audio, images, text, etc. in bytes. This conversion is possible through encode(). It take encoding technique as argument. By default, we use ‘UTF-8’ technique. >>> # Python Code to demonstrate string encoding >>> >>> # Initialising a String >>> x = ”TutorialsPoint” >>> >>> #Initialising a byte object >>> y = b”TutorialsPoint” >>> >>> # Using encode() to encode the String >>> # encoded version of x is stored in z using ASCII mapping >>> z = x.encode(”ASCII”) >>> >>> # Check if x is converted to bytes or not >>> >>> if(z==y): print(”Encoding Successful!”) else: print(”Encoding Unsuccessful!”) Encoding Successful! Converting bytes to text Converting bytes to text is called the decoding. This is implemented through decode(). We can convert a byte string to a character string if we know which encoding is used to encode it. So Encoding and decoding are inverse processes. >>> >>> # Python code to demonstrate Byte Decoding >>> >>> #Initialise a String >>> x = ”TutorialsPoint” >>> >>> #Initialising a byte object >>> y = b”TutorialsPoint” >>> >>> #using decode() to decode the Byte object >>> # decoded version of y is stored in z using ASCII mapping >>> z = y.decode(”ASCII”) >>> #Check if y is converted to String or not >>> if (z == x): print(”Decoding Successful!”) else: print(”Decoding Unsuccessful!”) Decoding Successful! >>> File I/O Operating systems represents files as a sequence of bytes, not text. A file is a named location on disk to store related information. It is used to permanently store data in your disk. In Python, a file operation takes place in the following order. Open a file Read or write onto a file (operation).Open a file Close the file. Python wraps the incoming (or outgoing) stream of bytes with appropriate decode (or encode) calls so

Python Libraries

Object Oriented Python – Libraries ”; Previous Next Requests − Python Requests Module Requests is a Python module which is an elegant and simple HTTP library for Python. With this you can send all kinds of HTTP requests. With this library we can add headers, form data, multipart files and parameters and access the response data. As Requests is not a built-in module, so we need to install it first. You can install it by running the following command in the terminal − pip install requests Once you have installed the module, you can verify if the installation is successful by typing below command in the Python shell. import requests If the installation has been successful, you won’t see any error message. Making a GET Request As a means of example we’ll be using the “pokeapi” Output − Making POST Requests The requests library methods for all of the HTTP verbs currently in use. If you wanted to make a simple POST request to an API endpoint then you can do that like so − req = requests.post(‘http://api/user’, data = None, json = None) This would work in exactly the same fashion as our previous GET request, however it features two additional keyword parameters − data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request. json which can be populated with a json object that will be passed in the body of our HTTP request also. Pandas: Python Library Pandas Pandas is an open-source Python Library providing high-performance data manipulation and analysis tool using its powerful data structures. Pandas is one of the most widely used Python libraries in data science. It is mainly used for data munging, and with good reason: Powerful and flexible group of functionality. Built on Numpy package and the key data structure is called the DataFrame. These dataframes allows us to store and manipulate tabular data in rows of observations and columns of variables. There are several ways to create a DataFrame. One way is to use a dictionary. For example − Output From the output we can see new brics DataFrame, Pandas has assigned a key for each country as the numerical values 0 through 4. If instead of giving indexing values from 0 to 4, we would like to have different index values, say the two letter country code, you can do that easily as well − Adding below one lines in the above code, gives brics.index = [”BR”, ”RU”, ”IN”, ”CH”, ”SA”] Output Indexing DataFrames Output Pygame Pygame is the open source and cross-platform library that is for making multimedia applications including games. It includes computer graphics and sound libraries designed to be used with the Python programming language. You can develop many cool games with Pygame.’ Overview Pygame is composed of various modules, each dealing with a specific set of tasks. For example, the display module deals with the display window and screen, the draw module provides functions to draw shapes and the key module works with the keyboard. These are just some of the modules of the library. The home of the Pygame library is at https://www.pygame.org/news To make a Pygame application, you follow these steps − Import the Pygame library import pygame Initialize the Pygame library pygame.init() Create a window. screen = Pygame.display.set_mode((560,480)) Pygame.display.set_caption(‘First Pygame Game’) Initialize game objects In this step we load images, load sounds, do object positioning, set up some state variables, etc. Start the game loop. It is just a loop where we continuously handle events, checks for input, move objects, and draw them. Each iteration of the loop is called a frame. Let’s put all the above logic into one below program, Pygame_script.py Output Beautiful Soup: Web Scraping with Beautiful Soup The general idea behind web scraping is to get the data that exists on a website, and convert it into some format that is usable for analysis. It’s a Python library for pulling data out of HTML or XML files. With your favourite parser it provide idiomatic ways of navigating, searching and modifying the parse tree. As BeautifulSoup is not a built-in library, we need to install it before we try to use it. To install BeautifulSoup, run the below command $ apt-get install Python-bs4 # For Linux and Python2 $ apt-get install Python3-bs4 # for Linux based system and Python3. $ easy_install beautifulsoup4 # For windows machine, Or $ pip instal beatifulsoup4 # For window machine Once the installation is done, we are ready to run few examples and explores Beautifulsoup in details, Output Below are some simple ways to navigate that data structure − One common task is extracting all the URLs found within a page’s <a> tags − Another common task is extracting all the text from a page − Print Page Previous Next Advertisements ”;

Environment Setup

Object Oriented Python – Environment Setup ”; Previous Next This chapter will explain in detail about setting up the Python environment on your local computer. Prerequisites and Toolkits Before you proceed with learning further on Python, we suggest you to check whether the following prerequisites are met − Latest version of Python is installed on your computer An IDE or text editor is installed You have basic familiarity to write and debug in Python, that is you can do the following in Python − Able to write and run Python programs. Debug programs and diagnose errors. Work with basic data types. Write for loops, while loops, and if statements Code functions If you don’t have any programming language experience, you can find lots of beginner tutorials in Python on https://www.tutorialpoints.com/ Installing Python The following steps show you in detail how to install Python on your local computer − Step 1 − Go to the official Python website https://www.python.org/, click on the Downloads menu and choose the latest or any stable version of your choice. Step 2 − Save the Python installer exe file that you’re downloading and once you have downloaded it, open it. Click on Run and choose Next option by default and finish the installation. Step 3 − After you have installed, you should now see the Python menu as shown in the image below. Start the program by choosing IDLE (Python GUI). This will start the Python shell. Type in simple commands to check the installation. Choosing an IDE An Integrated Development Environment is a text editor geared towards software development. You will have to install an IDE to control the flow of your programming and to group projects together when working on Python. Here are some of IDEs avaialable online. You can choose one at your convenience. Pycharm IDE Komodo IDE Eric Python IDE Note − Eclipse IDE is mostly used in Java, however it has a Python plugin. Pycharm Pycharm, the cross-platform IDE is one of the most popular IDE currently available. It provides coding assistance and analysis with code completion, project and code navigation, integrated unit testing, version control integration, debugging and much more Download link https://www.jetbrains.com/pycharm/download/#section=windows Languages Supported − Python, HTML, CSS, JavaScript, Coffee Script, TypeScript, Cython,AngularJS, Node.js, template languages. Screenshot Why to Choose? PyCharm offers the following features and benefits for its users − Cross platform IDE compatible with Windows, Linux, and Mac OS Includes Django IDE, plus CSS and JavaScript support Includes thousands of plugins, integrated terminal and version control Integrates with Git, SVN and Mercurial Offers intelligent editing tools for Python Easy integration with Virtualenv, Docker and Vagrant Simple navigation and search features Code analysis and refactoring Configurable injections Supports tons of Python libraries Contains Templates and JavaScript debuggers Includes Python/Django debuggers Works with Google App Engine, additional frameworks and libraries. Has customizable UI, VIM emulation available Komodo IDE It is a polyglot IDE which supports 100+ languages and basically for dynamic languages such as Python, PHP and Ruby. It is a commercial IDE available for 21 days free trial with full functionality. ActiveState is the software company managing the development of the Komodo IDE. It also offers a trimmed version of Komodo known as Komodo Edit for simple programming tasks. This IDE contains all kinds of features from most basic to advanced level. If you are a student or a freelancer, then you can buy it almost half of the actual price. However, it’s completely free for teachers and professors from recognized institutions and universities. It got all the features you need for web and mobile development, including support for all your languages and frameworks. Download link The download links for Komodo Edit(free version) and Komodo IDE(paid version) are as given here − Komodo Edit (free) https://www.activestate.com/komodo-edit Komodo IDE (paid) https://www.activestate.com/komodo-ide/downloads/ide Screenshot Why to Choose? Powerful IDE with support for Perl, PHP, Python, Ruby and many more. Cross-Platform IDE. It includes basic features like integrated debugger support, auto complete, Document Object Model(DOM) viewer, code browser, interactive shells, breakpoint configuration, code profiling, integrated unit testing. In short, it is a professional IDE with a host of productivity-boosting features. Eric Python IDE It is an open-source IDE for Python and Ruby. Eric is a full featured editor and IDE, written in Python. It is based on the cross platform Qt GUI toolkit, integrating the highly flexible Scintilla editor control. The IDE is very much configurable and one can choose what to use and what not. You can download Eric IDE from below link: https://eric-ide.python-projects.org/eric-download.html Why to Choose Great indentation, error highlighting. Code assistance Code completion Code cleanup with PyLint Quick search Integrated Python debugger. Screenshot Choosing a Text Editor You may not always need an IDE. For tasks such as learning to code with Python or Arduino, or when working on a quick script in shell script to help you automate some tasks a simple and light weight code-centric text editor will do. Also many text editors offer features such as syntax highlighting and in-program script execution, similar to IDEs. Some of the text editors are given here − Atom Sublime Text Notepad++ Atom Text Editor Atom is a hackable text editor built by the team of GitHub. It is a free and open source text and code editor which means that all the code is available for you to read, modify for your own use and even contribute improvements. It is a cross-platform text editor compatible for macOS, Linux, and Microsoft Windows with support for plug-ins written in Node.js and embedded Git Control. Download link https://atom.io/ Screenshot Languages Supported C/C++, C#, CSS, CoffeeScript, HTML, JavaScript, Java, JSON, Julia, Objective-C, PHP, Perl, Python, Ruby on Rails, Ruby, Shell script, Scala, SQL, XML, YAML and many more. Sublime Text Editor Sublime text is a proprietary software and it offers you a free trial version to test it before you purchase it. According to stackoverflow.com, it’s the fourth most popular Development Environment. Some of the advantages it provides is

Python Design Pattern

Python Design Pattern ”; Previous Next Overview Modern software development needs to address complex business requirements. It also needs to take into account factors such as future extensibility and maintainability. A good design of a software system is vital to accomplish these goals. Design patterns play an important role in such systems. To understand design pattern, let’s consider below example − Every car’s design follows a basic design pattern, four wheels, steering wheel, the core drive system like accelerator-break-clutch, etc. So, all things repeatedly built/ produced, shall inevitably follow a pattern in its design.. it cars, bicycle, pizza, atm machines, whatever…even your sofa bed. Designs that have almost become standard way of coding some logic/mechanism/technique in software, hence come to be known as or studied as, Software Design Patterns. Why is Design Pattern Important? Benefits of using Design Patterns are − Helps you to solve common design problems through a proven approach. No ambiguity in the understanding as they are well documented. Reduce the overall development time. Helps you deal with future extensions and modifications with more ease than otherwise. May reduce errors in the system since they are proven solutions to common problems. Classification of Design Patterns The GoF (Gang of Four) design patterns are classified into three categories namely creational, structural and behavioral. Creational Patterns Creational design patterns separate the object creation logic from the rest of the system. Instead of you creating objects, creational patterns creates them for you. The creational patterns include Abstract Factory, Builder, Factory Method, Prototype and Singleton. Creational Patterns are not commonly used in Python because of the dynamic nature of the language. Also language itself provide us with all the flexibility we need to create in a sufficient elegant fashion, we rarely need to implement anything on top, like singleton or Factory. Also these patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using a new operator. Structural Patterns Sometimes instead of starting from scratch, you need to build larger structures by using an existing set of classes. That’s where structural class patterns use inheritance to build a new structure. Structural object patterns use composition/ aggregation to obtain a new functionality. Adapter, Bridge, Composite, Decorator, Façade, Flyweight and Proxy are Structural Patterns. They offers best ways to organize class hierarchy. Behavioral Patterns Behavioral patterns offers best ways of handling communication between objects. Patterns comes under this categories are: Visitor, Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy and Template method are Behavioral Patterns. Because they represent the behavior of a system, they are used generally to describe the functionality of software systems. Commonly used Design Patterns Singleton It is one of the most controversial and famous of all design patterns. It is used in overly object-oriented languages, and is a vital part of traditional object-oriented programming. The Singleton pattern is used for, When logging needs to be implemented. The logger instance is shared by all the components of the system. The configuration files is using this because cache of information needs to be maintained and shared by all the various components in the system. Managing a connection to a database. Here is the UML diagram, class Logger(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, ”_logger”): cls._logger = super(Logger, cls).__new__(cls, *args, **kwargs) return cls._logger In this example, Logger is a Singleton. When __new__ is called, it normally constructs a new instance of that class. When we override it, we first check if our singleton instance has been created or not. If not, we create it using a super call. Thus, whenever we call the constructor on Logger, we always get the exact same instance. >>> >>> obj1 = Logger() >>> obj2 = Logger() >>> obj1 == obj2 True >>> >>> obj1 <__main__.Logger object at 0x03224090> >>> obj2 <__main__.Logger object at 0x03224090> Print Page Previous Next Advertisements ”;

Object Serialization

Object Oriented Python – Object Serialization ”; Previous Next In the context of data storage, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted and reconstructed later. In serialization, an object is transformed into a format that can be stored, so as to be able to deserialize it later and recreate the original object from the serialized format. Pickle Pickling is the process whereby a Python object hierarchy is converted into a byte stream (usually not human readable) to be written to a file, this is also known as Serialization. Unpickling is the reverse operation, whereby a byte stream is converted back into a working Python object hierarchy. Pickle is operationally simplest way to store the object. The Python Pickle module is an object-oriented way to store objects directly in a special storage format. What can it do? Pickle can store and reproduce dictionaries and lists very easily. Stores object attributes and restores them back to the same State. What pickle can’t do? It does not save an objects code. Only it’s attributes values. It cannot store file handles or connection sockets. In short we can say, pickling is a way to store and retrieve data variables into and out from files where variables can be lists, classes, etc. To Pickle something you must − import pickle Write a variable to file, something like pickle.dump(mystring, outfile, protocol), where 3rd argument protocol is optional To unpickling something you must − Import pickle Write a variable to a file, something like myString = pickle.load(inputfile) Methods The pickle interface provides four different methods. dump() − The dump() method serializes to an open file (file-like object). dumps() − Serializes to a string load() − Deserializes from an open-like object. loads() − Deserializes from a string. Based on above procedure, below is an example of “pickling”. Output My Cat pussy is White and has 4 legs Would you like to see her pickled? Here she is! b”x80x03c__main__nCatnqx00)x81qx01}qx02(Xx0ex00x00x00number_of_legsqx03Kx04Xx05x00x00x00colorqx04Xx05x00x00x00Whiteqx05ub.” So, in the example above, we have created an instance of a Cat class and then we’ve pickled it, transforming our “Cat” instance into a simple array of bytes. This way we can easily store the bytes array on a binary file or in a database field and restore it back to its original form from our storage support in a later time. Also if you want to create a file with a pickled object, you can use the dump() method ( instead of the dumps*()* one) passing also an opened binary file and the pickling result will be stored in the file automatically. [….] binary_file = open(my_pickled_Pussy.bin”, mode=”wb”) my_pickled_Pussy = pickle.dump(Pussy, binary_file) binary_file.close() Unpickling The process that takes a binary array and converts it to an object hierarchy is called unpickling. The unpickling process is done by using the load() function of the pickle module and returns a complete object hierarchy from a simple bytes array. Let’s use the load function in our previous example. Output MeOw is black Pussy is white JSON JSON(JavaScript Object Notation) has been part of the Python standard library is a lightweight data-interchange format. It is easy for humans to read and write. It is easy to parse and generate. Because of its simplicity, JSON is a way by which we store and exchange data, which is accomplished through its JSON syntax, and is used in many web applications. As it is in human readable format, and this may be one of the reasons for using it in data transmission, in addition to its effectiveness when working with APIs. An example of JSON-formatted data is as follow − {“EmployID”: 40203, “Name”: “Zack”, “Age”:54, “isEmployed”: True} Python makes it simple to work with Json files. The module sused for this purpose is the JSON module. This module should be included (built-in) within your Python installation. So let’s see how can we convert Python dictionary to JSON and write it to a text file. JSON to Python Reading JSON means converting JSON into a Python value (object). The json library parses JSON into a dictionary or list in Python. In order to do that, we use the loads() function (load from a string), as follow − Output Below is one sample json file, data1.json {“menu”: { “id”: “file”, “value”: “File”, “popup”: { “menuitem”: [ {“value”: “New”, “onclick”: “CreateNewDoc()”}, {“value”: “Open”, “onclick”: “OpenDoc()”}, {“value”: “Close”, “onclick”: “CloseDoc()”} ] } }} Above content (Data1.json) looks like a conventional dictionary. We can use pickle to store this file but the output of it is not human readable form. JSON(Java Script Object Notification) is a very simple format and that’s one of the reason for its popularity. Now let’s look into json output through below program. Output Above we open the json file (data1.json) for reading, obtain the file handler and pass on to json.load and getting back the object. When we try to print the output of the object, its same as the json file. Although the type of the object is dictionary, it comes out as a Python object. Writing to the json is simple as we saw this pickle. Above we load the json file, add another key value pair and writing it back to the same json file. Now if we see out data1.json, it looks different .i.e. not in the same format as we see previously. To make our Output looks same (human readable format), add the couple of arguments into our last line of the program, json.dump(conf, fh, indent = 4, separators = (‘,’, ‘: ‘)) Similarly like pickle, we can print the string with dumps and load with loads. Below is an example of that, YAML YAML may be the most human friendly data serialization standard for all programming languages. Python yaml module is called pyaml YAML is an alternative to JSON − Human readable code − YAML is the most human readable format so much so that

Introduction

Object Oriented Python – Introduction ”; Previous Next Programming languages are emerging constantly, and so are different methodologies.Object-oriented programming is one such methodology that has become quite popular over past few years. This chapter talks about the features of Python programming language that makes it an object-oriented programming language. Language Programming Classification Scheme Python can be characterized under object-oriented programming methodologies. The following image shows the characteristics of various programming languages. Observe the features of Python that makes it object-oriented. Langauage Classes Categories Langauages Programming Paradigm Procedural C, C++, C#, Objective-C, java, Go Scripting CoffeeScript, JavaScript, Python, Perl, Php, Ruby Functional Clojure, Eralang, Haskell, Scala Compilation Class Static C, C++, C#, Objective-C, java, Go, Haskell, Scala Dynamic CoffeeScript, JavaScript, Python, Perl, Php, Ruby, Clojure, Erlang Type Class Strong C#, java, Go, Python, Ruby, Clojure, Erlang, Haskell, Scala Weak C, C++, C#, Objective-C, CoffeeScript, JavaScript, Perl, Php Memory Class Managed Others Unmanaged C, C++, C#, Objective-C What is Object Oriented Programming? Object Oriented means directed towards objects. In other words, it means functionally directed towards modelling objects. This is one of the many techniques used for modelling complex systems by describing a collection of interacting objects via their data and behavior. Python, an Object Oriented programming (OOP), is a way of programming that focuses on using objects and classes to design and build applications.. Major pillars of Object Oriented Programming (OOP) are Inheritance, Polymorphism, Abstraction, ad Encapsulation. Object Oriented Analysis(OOA) is the process of examining a problem, system or task and identifying the objects and interactions between them. Why to Choose Object Oriented Programming? Python was designed with an object-oriented approach. OOP offers the following advantages − Provides a clear program structure, which makes it easy to map real world problems and their solutions. Facilitates easy maintenance and modification of existing code. Enhances program modularity because each object exists independently and new features can be added easily without disturbing the existing ones. Presents a good framework for code libraries where supplied components can be easily adapted and modified by the programmer. Imparts code reusability Procedural vs. Object Oriented Programming Procedural based programming is derived from structural programming based on the concepts of functions/procedure/routines. It is easy to access and change the data in procedural oriented programming. On the other hand, Object Oriented Programming (OOP) allows decomposition of a problem into a number of units called objects and then build the data and functions around these objects. It emphasis more on the data than procedure or functions. Also in OOP, data is hidden and cannot be accessed by external procedure. The table in the following image shows the major differences between POP and OOP approach. Difference between Procedural Oriented Programming(POP)vs. Object Oriented Programming(OOP). Procedural Oriented Programming ObjectOriented Programming Based On In Pop,entire focus is on data and functions Oops is based on a real world scenario.Whole program is divided into small parts called object Reusability Limited Code reuse Code reuse Approach Top down Approach Object focused Design Access specifiers Not any Public, private and Protected Data movement Data can move freely from functions to function in the system In Oops, data can move and communicate with each other through member functions Data Access In pop, most functions uses global data for sharing that can be accessed freely from function to function in the system In Oops,data cannot move freely from method to method,it can be kept in public or private so we can control the access of data Data Hiding In pop, so specific way to hide data, so little bit less secure It provides data hiding, so much more secure Overloading Not possible Functions and Operator Overloading Example-Languages C, VB, Fortran, Pascal C++, Python, Java, C# Abstraction Uses abstraction at procedure level Uses abstraction at class and object Level Principles of Object Oriented Programming Object Oriented Programming (OOP) is based on the concept of objects rather than actions, and data rather than logic. In order for a programming language to be object-oriented, it should have a mechanism to enable working with classes and objects as well as the implementation and usage of the fundamental object-oriented principles and concepts namely inheritance, abstraction, encapsulation and polymorphism. Let us understand each of the pillars of object-oriented programming in brief − Encapsulation This property hides unnecessary details and makes it easier to manage the program structure. Each object’s implementation and state are hidden behind well-defined boundaries and that provides a clean and simple interface for working with them. One way to accomplish this is by making the data private. Inheritance Inheritance, also called generalization, allows us to capture a hierarchal relationship between classes and objects. For instance, a ‘fruit’ is a generalization of ‘orange’. Inheritance is very useful from a code reuse perspective. Abstraction This property allows us to hide the details and expose only the essential features of a concept or object. For example, a person driving a scooter knows that on pressing a horn, sound is emitted, but he has no idea about how the sound is actually generated on pressing the horn. Polymorphism Poly-morphism means many forms. That is, a thing or action is present in different forms or ways. One good example of polymorphism is constructor overloading in classes. Object-Oriented Python The heart of Python programming is object and OOP, however you need not restrict yourself to use the OOP by organizing your code into classes. OOP adds to the whole design philosophy of Python and encourages a clean and pragmatic way to programming. OOP also enables in writing bigger and complex programs. Modules vs. Classes and Objects Modules are like “Dictionaries” When working on Modules, note the following points − A Python module is a package to encapsulate reusable code. Modules reside in a folder with a __init__.py file on it. Modules contain functions and classes. Modules are imported using the import keyword. Recall that a dictionary is a key-value pair. That means if you have a dictionary with a key EmployeID and you want to

Useful Resources

Object Oriented Python – Useful Resources ”; Previous Next The following resources contain additional information on Object oriented Python. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Python Flask and SQLAlchemy ORM 22 Lectures 1.5 hours Jack Chan More Detail Python and Elixir Programming Bundle Course 81 Lectures 9.5 hours Pranjal Srivastava More Detail TKinter Course – Build Python GUI Apps 49 Lectures 4 hours John Elder More Detail A Beginner”s Guide to Python and Data Science 81 Lectures 8.5 hours Datai Team Academy More Detail Deploy Face Recognition Project With Python, Django, And Machine Learning Best Seller 93 Lectures 6.5 hours Srikanth Guskra More Detail Professional Python Web Development with Flask 80 Lectures 12 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;

Advanced Features

Object Oriented Python – Advanced Features ”; Previous Next In this we will look into some of the advanced features which Python provide Core Syntax in our Class design In this we will look onto, how Python allows us to take advantage of operators in our classes. Python is largely objects and methods call on objects and this even goes on even when its hidden by some convenient syntax. >>> var1 = ”Hello” >>> var2 = ” World!” >>> var1 + var2 ”Hello World!” >>> >>> var1.__add__(var2) ”Hello World!” >>> num1 = 45 >>> num2 = 60 >>> num1.__add__(num2) 105 >>> var3 = [”a”, ”b”] >>> var4 = [”hello”, ” John”] >>> var3.__add__(var4) [”a”, ”b”, ”hello”, ” John”] So if we have to add magic method __add__ to our own classes, could we do that too. Let’s try to do that. We have a class called Sumlist which has a contructor __init__ which takes list as an argument called my_list. class SumList(object): def __init__(self, my_list): self.mylist = my_list def __add__(self, other): new_list = [ x + y for x, y in zip(self.mylist, other.mylist)] return SumList(new_list) def __repr__(self): return str(self.mylist) aa = SumList([3,6, 9, 12, 15]) bb = SumList([100, 200, 300, 400, 500]) cc = aa + bb # aa.__add__(bb) print(cc) # should gives us a list ([103, 206, 309, 412, 515]) Output [103, 206, 309, 412, 515] But there are many methods which are internally managed by others magic methods. Below are some of them, ”abc” in var # var.__contains__(”abc”) var == ”abc” # var.__eq__(”abc”) var[1] # var.__getitem__(1) var[1:3] # var.__getslice__(1, 3) len(var) # var.__len__() print(var) # var.__repr__() Inheriting From built-in types Classes can also inherit from built-in types this means inherits from any built-in and take advantage of all the functionality found there. In below example we are inheriting from dictionary but then we are implementing one of its method __setitem__. This (setitem) is invoked when we set key and value in the dictionary. As this is a magic method, this will be called implicitly. class MyDict(dict): def __setitem__(self, key, val): print(”setting a key and value!”) dict.__setitem__(self, key, val) dd = MyDict() dd[”a”] = 10 dd[”b”] = 20 for key in dd.keys(): print(”{0} = {1}”.format(key, dd[key])) Output setting a key and value! setting a key and value! a = 10 b = 20 Let’s extend our previous example, below we have called two magic methods called __getitem__ and __setitem__ better invoked when we deal with list index. # Mylist inherits from ”list” object but indexes from 1 instead for 0! class Mylist(list): # inherits from list def __getitem__(self, index): if index == 0: raise IndexError if index > 0: index = index – 1 return list.__getitem__(self, index) # this method is called when # we access a value with subscript like x[1] def __setitem__(self, index, value): if index == 0: raise IndexError if index > 0: index = index – 1 list.__setitem__(self, index, value) x = Mylist([”a”, ”b”, ”c”]) # __init__() inherited from builtin list print(x) # __repr__() inherited from builtin list x.append(”HELLO”); # append() inherited from builtin list print(x[1]) # ”a” (Mylist.__getitem__ cutomizes list superclass # method. index is 1, but reflects 0! print (x[4]) # ”HELLO” (index is 4 but reflects 3! Output [”a”, ”b”, ”c”] a HELLO In above example, we set a three item list in Mylist and implicitly __init__ method is called and when we print the element x, we get the three item list ([‘a’,’b’,’c’]). Then we append another element to this list. Later we ask for index 1 and index 4. But if you see the output, we are getting element from the (index-1) what we have asked for. As we know list indexing start from 0 but here the indexing start from 1 (that’s why we are getting the first item of the list). Naming Conventions In this we will look into names we’ll used for variables especially private variables and conventions used by Python programmers worldwide. Although variables are designated as private but there is not privacy in Python and this by design. Like any other well documented languages, Python has naming and style conventions that it promote although it doesn’t enforce them. There is a style guide written by “Guido van Rossum” the originator of Python, that describe the best practices and use of name and is called PEP8. Here is the link for this, https://www.python.org/dev/peps/pep-0008/ PEP stands for Python enhancement proposal and is a series of documentation that distributed among the Python community to discuss proposed changes. For example it is recommended all, Module names − all_lower_case Class names and exception names − CamelCase Global and local names − all_lower_case Functions and method names − all_lower_case Constants − ALL_UPPER_CASE These are just the recommendation, you can vary if you like. But as most of the developers follows these recommendation so might me your code is less readable. Why conform to convention? We can follow the PEP recommendation we it allows us to get, More familiar to the vast majority of developers Clearer to most readers of your code. Will match style of other contributers who work on same code base. Mark of a professional software developers Everyone will accept you. Variable Naming − ‘Public’ and ‘Private’ In Python, when we are dealing with modules and classes, we designate some variables or attribute as private. In Python, there is no existence of “Private” instance variable which cannot be accessed except inside an object. Private simply means they are simply not intended to be used by the users of the code instead they are intended to be used internally. In general, a convention is being followed by most Python developers i.e. a name prefixed with an underscore for example. _attrval (example below) should be treated as a non-public part of the API or any Python code, whether it is a function, a method or a data member. Below is the naming convention we follow, Public attributes or variables (intended to be used by the importer of

Home

Object Oriented Python Tutorial PDF Version Quick Guide Resources Job Search Discussion Python has been an object-oriented language since it existed. In this tutorial we will try to get in-depth features of OOPS in Python programming. Audience This tutorial has been prepared for the beginners and intermediate to help them understand the Python Oops features and concepts through programming. Prerequisites Understanding on basic of Python programming language will help to understand and learn quickly. If you are new to programming, it is recommended to first go through “Python for beginners” tutorials. Print Page Previous Next Advertisements ”;