IT Specialist Python - Session 5
IT Specialist Python - Session 5
Why OOP?
Object Oriented Programming allows code to be reusable, organized, and easy to
maintain. Follows the software development principle used by many programmers
DRY (Don’t Repeat Yourself), to avoid duplicating the code and this create efficient
programs.
Why OOP?
A class is a template.
It defines in a generic way how the objects of a certain type are going to be. For
example, a class to represent animals can be called 'animal' and have a series of
attributes, such as 'name' or 'age' (which are normally properties), and a series
with the behaviors that these can have, such as walking or eat, and which in turn
are implemented as methods of the class (functions).
classes in python
Python is an object-oriented programming language.
Doesn't have to be named self, you can call it whatever you want, but it has to be
the first parameter of any function in the class:
Modify or Delete property
Modify property
You can modify properties on objects like this:
Delete property
You can remove properties on objects using the keyword del:
Delete object
You can remove objects using the keyword del:
Exercise
Create a Calculator object that has the qualities:
Properties:
• Owner
• Model
• Record
methods
• Start, you must run a menu to perform basic operations
• Addition
• Subtraction
• Multiplication
• Division
• View Operations History
Python inheritance
Inheritance allows us to define a class that inherits all the methods and properties
of another class.
The Secondary class is the class that inherits from another class,
also called derived class.
Python inheritance
Create a main class
Any class can be a main class, so the syntax is the same as creating any
other class:
Figure
Geometric
Python inheritance
Create a class called people, with properties: firstname, lastname and a
method printname:
Python inheritance
Create a child class
To create a class that inherits functionality from another class, pass the
parent class as a parameter when creating the child class:
Create a class called Student, which will inherit the properties and
methods of the class people:
Now the Student class has the same properties and methods as the
Person class.
Python inheritance
Add function __init__()
So far we've created a child class that inherits its parent's properties
and methods.
We want to add the __init__() function to the child class (instead of the
keywordpass).
Python inheritance
Use the super() function
Python also has a super() function that will cause the child class to
inherit all of its parent's methods and properties:
Exercise
Create a shape class that derives different geometric figures and that
allows calculating their areas and knowing their sides.
Doubts or Questions