Python__OOP Lab 14 (1)
Python__OOP Lab 14 (1)
Engineering
Riphah College of Science & Technology
Faculty of Engineering & Applied Sciences
Riphah International University, Lahore
OBJECTIVES:
(i) To get introduced to the concept of Classes
(ii) To use Objects and Methods of a Class
Name: ….…………………………………………………………
SAP: ……………………………………………………………
EEDEPARTMENT
THEORY
Python Classes/Objects
Python Classes
A class is considered a blueprint of objects. We can think of the class as a sketch (prototype)
of a house. It contains all the details about the floors, doors, windows, etc. Based on these
descriptions, we build the house; the house is the object. Since many houses can be made
from the same description, we can create many objects from a class.
class Name:
# class definition
class Bike:
name = ""
gear = 0
Here,
EEDEPARTMENT
Python Objects
An object is called an instance of a class. Suppose Bike is a class then we can create objects
like bike1, bike2, etc from the class. Here's the syntax to create an object.
objectName = ClassName()
# create class
class Bike:
name = ""
gear = 0
Here, bike1 is the object of the class. Now, we can use this object to access the class attributes.
# define a class
class Bike:
name = ""
gear = 0
EEDEPARTMENT
We can also create multiple objects from a single class. For example,
Example
# define a class
class Employee:
# define a property
employee_id = 0
Python Methods
We can also define a function inside a Python class. A Python function defined inside a class
is called a method.
Example 2
EEDEPARTMENT
Method: calculate_area()
Here, we have created an object named study_room from the Room class. We then used the
object to assign values to attributes: length and breadth. Notice that we have also used the
object to call the method inside the class,
Python Constructors
class Bike:
name = ""
...
# create object
bike1 = Bike()
However, we can also initialize values using the constructors. For example,
class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
Here, __init__() is the constructor function that is called whenever a new object of that class is
instantiated. The constructor above initializes the value of the name attribute. We have used
the self.name to refer to the name attribute of the bike1 object. If we use a constructor to
initialize values inside a class, we need to pass the corresponding value during the object
creation of the class.
EEDEPARTMENT
The self, parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class. It does not have to be named self, you can call it whatever
you like, but it has to be the first parameter of any function in the class:
Lab Task
Task 1
Make modification to example 1 and 2 to show your understanding.
Task 2
Create a class name semester with two methods of your choice to show semester class can be
used.
Conclusion