Classes and Packages – Complete Python Notes
3.1 Define Class with its Members and Create Instances of Class
A class is a blueprint for creating objects.
Members of a class:
• Data Members (Variables)
• Member Functions (Methods)
Example:
class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks
def display(self):
print([Link], [Link])
# Creating object (instance)
s1 = Student("Rizwan", 95)
[Link]()
3.2 Implement Different Types of Inheritance
Inheritance allows one class to acquire properties of another class.
Types:
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
Example (Single Inheritance):
class Parent:
def show(self):
print("Parent Class")
class Child(Parent):
pass
c = Child()
[Link]()
3.3 Use super() to Call Methods of Super Class
super() is used to call parent class constructor or methods.
Example:
class Parent:
def __init__(self):
print("Parent Constructor")
class Child(Parent):
def __init__(self):
super().__init__()
print("Child Constructor")
3.4 Use Python Identity Operator
Identity operators: is, is not
They compare memory locations of two objects.
Example:
a = [1,2,3]
b = a
print(a is b) # True
3.5 Create and Import Modules and Packages
Module: A Python file containing functions/classes.
Package: Collection of modules in a directory with __init__.py file.
Creating module ([Link]):
def greet():
print("Hello")
Importing:
import mymodule
[Link]()
3.6 Use Local and Global Variables
Local Variable: Declared inside function.
Global Variable: Declared outside function.
Example:
x = 10 # Global
def func():
y = 5 # Local
print(x + y)
3.7 Set Up Virtual Environment
Virtual environment isolates project dependencies.
Steps:
1. python -m venv myenv
2. myenv\Scripts\activate (Windows)
3. source myenv/bin/activate (Linux/Mac)
4. deactivate (to exit)
3.8 Install Packages
Use pip to install packages.
Examples:
pip install numpy
pip install pandas
Check installed packages:
pip list
3.9 Use Standard Mathematical Functions
Import math module.
Functions:
• sqrt()
• cos()
• sin()
• pow()
• degrees()
• fabs()
Example:
import math
print([Link](25))
print([Link](0))
3.10 Use datetime Package
datetime module handles date and time.
Example:
import datetime
now = [Link]()
print(now)
today = [Link]()
print(today)