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

1
2
class MyClass:
  x = 5

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# user class
class MyClass:

	# constructor
	def __init__(self):
		msg = "hello world"

	# accessing members
	def println(self):
		print(self.msg)

# creating the object
obj = MyClass()
obj.println()

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# user class
class MyClass:

	# constructor
	def __init__(self, arg):
		self.msg = "hello world"

	# accessing members
	def println(self):
		print(self.msg)

# creating the object
obj = MyClass("")
obj.println()

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:

1
2
3
4
5
6
7
8
9
# program written with lambda functions
# to print sum
func = lambda num1, num2:num1+num2
print(func(3,6))

# program done with functions
def add(num1, num2):
	return num1 + num2
print(add(3, 6))

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.

1
2
3
4
5
6
class MyData:
	# constructor to get the data
	def __init__(self, val):
		self.__x = val
	def printData(self):
		print(self.__x)

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

1
2
3
4
class MainClass:
    # methods/members
class DerivedClass(MainClass):
    # methods/members

Example of a program that follows polymorphism

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Vehicle:
	def __init__(self, cc, bhp):
		self.__cc = cc
		self.__bhp = bhp

	def printStd(self):
		print(f"The car is {self.__cc} cc and has {self.__bhp} bhp")

class OpenWheeler(Vehicle):
	def __init__(self, cc, bhp):
		super().__init__(cc, bhp)

	def getDownforce(self, downforce):
		self.__downforce = downforce

	def printStd(self):
		super().printStd()
		print(f"The car has {self.__downforce} downforce")

car1 = Vehicle('100', '9')
f11976 = OpenWheeler('3000', '500')
f11976.getDownforce('300')

car1.printStd()
f11976.printStd()

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

1
isinstance(object, classinfo)

Here is an example of the isinstance() function showing the difference between two inherited classes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Animal:
  def speak(self):
    print("I am an animal")

class Dog(Animal):
  def speak(self):
    print("Woof!")

d = Dog()

print(isinstance(d, Animal))    # True
print(isinstance(d, Dog))       # True
print(isinstance(d, str))       # False

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

  1. Python 3
  2. Pip

Steps

  1. Installing virtual environemnt package

    • Windows
      1
      
      pip install virtualenv
      
    • Linux
      1
      
      pip3 install virtualenv
      
  2. Creating virtual environent

    • Windows - cmd/powershell
      1
      
      py -m venv {your_env_name}
      
    • Linux
      1
      
      python3 -m venv myworld
      
  3. Activating virtual environemt

    • Windows - cmd
      1
      
      myworld\Scripts\activate.bat
      
    • Windows - powershell
      1
      
      myworld\Scripts\activate.ps1
      
    • Linux
      1
      
      source myworld/bin/activate
      
  4. Downloading required packages

    • Windows
      1
      
      py -m pip install {required_package}
      
    • Linux
      1
      
      python3 -m pip3 install {required_package}