Unit 5 - OOPs in Python
Unit 5 - OOPs in Python
[email protected]
J732KOTCSB
Program: MCA
Specialization: Data Science
Semester: 2
Course Name: Python for Data Science
Course Code: 21VMT5S204
Unit Name: OOPs in Python
Learning Outcomes:
- Procedural Programming.
- Object Oriented Programming
- OOPs vs Procedural Programming
- Features of OOPs
- Classes:
[email protected]
J732KOTCSB
Syntax of classes
Example
- Objects
Syntax of objects
Example
- Difference between classes and objects
- Mini project.
Class:
A class is said to be a blueprint for an object. It is a user-defined data type. It is
a collection of objects. Data members and functions are held within a class.
For example, in a company, we evaluate two departments- HR and Accounting,
and we want to check which department a person works in. We write the
program. If say we enter the employ ID of person XYZ, we need to retrieve the
name of the employee and the department in which he works. For one entity,
it is easy to do so, but for multiple entries, in 1000s, it becomes very difficult.
Syntax of Class:
class employee_details():
To define a class, you simply write class, which is a keyword and the
className() fillowed by a semicolon. Inside the class you can write multiple
functions that are part of the class. According to access specifiers, the
functions within the class are accessible or inaccessible to rest of the program.
[email protected]
J732KOTCSBInside a class, make sure that everything is properly indented, just like in a
conditional statement.
Example of a class:
Objects:
Unless an object is created inside a class, no memory is allocated to the class.
Instantiation is creating an object of a class. The objector instance contains the
actual information.
object_name = class_name()
In the above example, to assign an object to a class, simply equate the object
name to the classname(). To display the value of the string inside
employee_details, you must simply print objectName.variableName.
[email protected]
J732KOTCSB
Class Object
Class is used to bind all the data into Objects are like variables of class.
a single unit.
It is a logical entity It is a physical entity.
Example: Example:
employee_details is a class employee_id, employee_name,
department.
The above examples are simple and are not usually used in python. For real
world applications, we use the __init__() function.
__init__() function:
[email protected]
J732KOTCSB
All classes have an __init__() function that is executed when the class is
intialised. It is called automatically whenever a class is used to create a new
object.
The __init__() function is similar to constructors. Constructors in java are used
to initialise the state of the object. It contains a set of statements that are
executed when the object is created and is run when the object is instantiated.
Example:
Mini Project:
[email protected]
J732KOTCSB
Example 2: Display 3 book names and their page counts using classes and
objects.
[email protected]
J732KOTCSB