Chapter summary - Unit 4
Object Oriented Programming:
Define and use your own classes: An introduction to classes and objects, define a class,
object composition, encapsulation;
Inheritance: Inheritance, override object methods;
Design an object oriented program: Techniques for object-oriented design
Text Book 1 – Chapters 14,15,16
Creating your own class
A class can be created in python by using the class keyword
This creates a blueprint for the objects to be defined. Methods and members can be defined in the class.
Constructors
Python classes need constructors to initialise the members and methods, it is initiated by the init keyword.
The self keyword acts as a self pointing object. Here when the object is generated the constructor is called and the msg variable is initiated. The usage of the self keyword is also crutial is called methods within classes.
This code can be also changed to accept paramatrised constructor
The self keyword here also sometimes acts like the super keyword in java.
Lambda functions
Lambda functions are functions are anoymous functions, it can have n number of arguments but can only have one expression.
Example:
Encapsulation
Encapsuation is the way of wrapping the data and the functions withing a class isolated from the ouytside interference. Encapsualation can be achieved in python by using private and public attributes at stretigic places to ensure the data safety.
Inheritance
Inheritance is a way for the derived class to get all the properties of base class including the class methods and class members.
Syntax of inheritance
Example of a program that follows polymorphism
| |
IsInstance in python
The isinstance() function in Python is used to check if an object is an instance of a specified class. The syntax of the isinstance() function is
| |
Here is an example of the isinstance() function showing the difference between two inherited classes
Virtual environments in python
Before proceeding to the packages module in python, it is important to know about virtual environments. Note that you may proceed to packages without knowing about virtual environments, however it is recommended to know about virtual environments because it helps in keeping isolated packages for different projects as some deprecated packages might not work on newer projects and similarly newer packages may not work on legacy projects.
Requiremnets
- Python 3
- Pip
Steps
Installing virtual environemnt package
Creating virtual environent
Activating virtual environemt
Downloading required packages