OOP In Python

3y ago
60 Views
9 Downloads
3.32 MB
111 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Matteo Vollmer
Transcription

i

OOP in PythonAbout the TutorialPython has been an object-oriented language since it existed. In this tutorial we will try toget in-depth features of OOPS in Python programming.AudienceThis tutorial has been prepared for the beginners and intermediate to help themunderstand the Python Oops features and concepts through programming.PrerequisitesUnderstanding on basic of Python programming language will help to understand and learnquickly. If you are new to programming, it is recommended to first go through “Python forbeginners” tutorials.ii

OOP in PythonTable of ContentsAbout the Tutorial . iiAudience. iiPrerequisites. iiOOP IN PYTHON – INTRODUCTION . 1Language Programming Classification Scheme . 1What is Object Oriented Programming? . 2Why to Choose Object-oriented programming?. 2Procedural vs. Object Oriented Programming . 2Principles of Object Oriented Programming . 3Object-Oriented Python . 5Modules vs. Classes and Objects . 5OOP IN PYTHON – ENVIRONMENT SETUP . 8Prerequisites and Toolkits . 8Installing Python . 8Choosing an IDE . 10Pycharm. 10Komodo IDE . 11Eric Python IDE . 12Choosing a Text Editor . 13Atom Text Editor . 13Screenshot of Atom text . 14Sublime Text Editor . 14Notepad . 15OOP IN PYTHON – DATA STRUCTURES . 17Lists . 17

OOP in PythonAccessing Items in Python List . 18Empty Objects . 18Tuples . 19Dictionary . 21Sets . 24OOP IN PYTHON – BUILDING BLOCKS. 28Class Bundles : Behavior and State . 28Creation and Instantiation . 29Instance Methods . 30Encapsulation . 31Init Constructor. 33Class Attributes. 34Working with Class and Instance Data . 35OOP IN PYTHON – OBJECT ORIENTED SHORTCUT . 37Python Built-in Functions . 37Default Arguments . 42OOP IN PYTHON – INHERITANCE AND POLYMORPHISM . 44Inheritance . 44Inheriting Attributes . 44Inheritance Examples. 45Polymorphism (“MANY SHAPES”) . 47Overriding. 48Inheriting the Constructor . 49Multiple Inheritance and the Lookup Tree . 50Decorators, Static and Class Methods . 54OOP IN PYTHON –PYTHON DESIGN PATTERN. 57i

OOP in PythonOverview . 57Why is Design Pattern Important? . 57Classification of Design Patterns . 57Commonly used Design Patterns . 58OOP IN PYTHON – ADVANCED FEATURES . 60Core Syntax in our Class design . 60Inheriting From built-in types . 61Naming Conventions. 63OOP IN PYTHON – FILES AND STRINGS . 65Strings. 66File I/O . 71OOP IN PYTHON – EXCEPTION AND EXCEPTION CLASSES. 72Identifying Exception (Errors) . 72Catching/Trapping Exception . 73Raising Exceptions . 75Creating Custom exception class . 76OOP IN PYTHON – OBJECT SERIALIZATION . 80Pickle . 80Methods . 81Unpickling . 82JSON . 82YAML . 85Installing YAML . 85PDB – The Python Debugger . 89Logging . 91Benchmarking . 93ii

OOP in Python12. OOP IN PYTHON – PYTHON LIBRARIES . 96Requests: Python Requests Module . 96Making a GET Request . 96Making POST Requests . 97Pandas: Python Library Pandas . 97Indexing DataFrames . 98Pygame . 99Beautiful Soup: Web Scraping with Beautiful Soup . 102iii

OOP in Python1. OOP in Python – IntroductionProgramming languages are emerging constantly, and so are different methodologies.Object-oriented programming is one such methodology that has become quite popularover past few years.This chapter talks about the features of Python programming language that makes it anobject-oriented programming language.Language Programming Classification SchemePython can be characterized under object-oriented programming methodologies. Thefollowing image shows the characteristics of various programming languages. Observe thefeatures of Python that makes it object-oriented.1

OOP in PythonWhat is Object Oriented Programming?Object Oriented means directed towards objects. In other words, it means functionallydirected towards modelling objects. This is one of the many techniques used for modellingcomplex systems by describing a collection of interacting objects via their data andbehavior.Python, an Object Oriented programming (OOP), is a way of programming that focuseson using objects and classes to design and build applications. Major pillars of ObjectOriented Programming (OOP) are Inheritance, Polymorphism, Abstraction, adEncapsulation.Object Oriented Analysis(OOA) is the process of examining a problem, system or task andidentifying the objects and interactions between them.Why to Choose Object Oriented Programming?Python was designed with an object-oriented approach. OOP offers the followingadvantages: Provides a clear program structure, which makes it easy to map real world problemsand their solutions. Facilitates easy maintenance and modification of existing code. Enhances program modularity because each object exists independently and newfeatures can be added easily without disturbing the existing ones. Presents a good framework for code libraries where supplied components can beeasily adapted and modified by the programmer. Imparts code reusabilityProcedural vs. Object Oriented ProgrammingProcedural based programming is derived from structural programming based on theconcepts of functions/procedure/routines. It is easy to access and change the data inprocedural oriented programming. On the other hand, Object Oriented Programming(OOP) allows decomposition of a problem into a number of units called objects and thenbuild the data and functions around these objects. It emphasis more on the data thanprocedure or functions. Also in OOP, data is hidden and cannot be accessed by externalprocedure.2

OOP in PythonThe table in the following image shows the major differences between POP and OOPapproach.Principles of Object Oriented ProgrammingObject Oriented Programming (OOP) is based on the concept of objects rather thanactions, and data rather than logic. In order for a programming language to be objectoriented, it should have a mechanism to enable working with classes and objects as wellas the implementation and usage of the fundamental object-oriented principles andconcepts namely inheritance, abstraction, encapsulation and polymorphism.3

OOP in PythonLet us understand each of the pillars of object-oriented programming in brief:EncapsulationThis property hides unnecessary details and makes it easier to manage the programstructure. Each object’s implementation and state are hidden behind well-definedboundaries and that provides a clean and simple interface for working with them. One wayto accomplish this is by making the data private.InheritanceInheritance, also called generalization, allows us to capture a hierarchal relationshipbetween classes and objects. For instance, a ‘fruit’ is a generalization of ‘orange’.Inheritance is very useful from a code reuse perspective.AbstractionThis property allows us to hide the details and expose only the essential features of aconcept 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 pressingthe horn.PolymorphismPoly-morphism means many forms. That is, a thing or action is present in different formsor ways. One good example of polymorphism is constructor overloading in classes.4

OOP in PythonObject-Oriented PythonThe heart of Python programming is object and OOP, however you need not restrictyourself to use the OOP by organizing your code into classes. OOP adds to the wholedesign 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 ObjectsModules 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 akey EmployeID and you want to retrieve it, then you will have to use the following linesof code:employee {“EmployeID”: “Employee Unique Identity!”}print (employee [‘EmployeID])You will have to work on modules with the following process: A module is a Python file with some functions or variables in it. Import the file you need. Now, you can access the functions or variables in that module with the ‘.’ (dot)Operator.Consider a module named employee.py with a function in it called employee. The codeof the function is given below:# this goes in employee.pydef EmployeID():print (“Employee Unique Identity!”)Now import the module and then access the function EmployeID:import employeeemployee. EmployeID()5

OOP in PythonYou can insert a variable in it named Age, as shown:def EmployeID():print (“Employee Unique Identity!”)# just a variableAge “Employee age is **”Now, access that variable in the following way:import , let’s compare this to dictionary:Employee[‘EmployeID’]# get EmployeID from employeeEmployee.employeID()# get employeID from the moduleEmployee.Age# get access to variableNotice that there is common pattern in Python: Take a key value style container Get something out of it by the key’s nameWhen comparing module with a dictionary, both are similar, except with the following: In the case of the dictionary, the key is a string and the syntax is [key]. In the case of the module, the key is an identifier, and the syntax is .key.Classes are like ModulesModule is a specialized dictionary that can store Python code so you can get to it with the‘.’ Opera

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.

Related Documents:

Some OOP features can be implemented in C or other procedural programming languages, but not enforced by these languages OOP languages: OOP concepts are embeded in and enforced by the languages. OOP Concepts 29 OOP languages vary in degrees of object-oriented Pure: Smalltalk, Eiffel, Ruby, JADE. Original OO plus some procedural features .

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

(3) The object-oriented programming (OOP) in Python is simple flexibility while Matlab's OOP scheme is complex and confusing. (4) Python is free and open. a. While Python is open source programming, much of Matlab is closed b. The developers of Python encoura

9/5/22 Compsci 201, Fall 2022, OOP 3. Recapping some Java Themes 9/5/22 Compsci 201, Fall 2022, OOP 4. Comments on Java Style Code blocks: Opening {ends first line of if, for, while, or method . Aside: Python uses objects too 9/5/22 Compsci 201, Fall 2022, OOP 15 Split is a methodwe are calling on this String object, not a