Python - OOP - Object Oriented Programming - Part 1
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code to manipulate that data. OOP is widely used in many programming languages, including Python.
Here are some key OOP terminology in Python:
- Class: A blueprint for creating objects. A class defines a set of attributes and methods that describe the object's properties and behavior.
- Object: An instance of a class. Objects have state (attributes) and behavior (methods).
- Attribute: A variable that belongs to an object. Attributes define the state of an object.
- Method: A function that belongs to a class. Methods define the behavior of an object.
Inheritance: A mechanism in which one class acquires the properties (attributes and methods) of another class. The class that inherits is called the subclass, and the class that is inherited from is called the superclass.
Polymorphism: The ability of objects to take on different forms or types. Polymorphism allows objects of different classes to be used interchangeably.
Encapsulation: The idea of hiding the internal workings of an object and exposing a public interface. Encapsulation allows for more secure and stable code.
These are just a few of the key OOP terminology in Python. Understanding these concepts is essential for creating effective and efficient object-oriented programs.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_make(self):
return self.make
def get_model(self):
return self.model
def get_year(self):
return self.year
my_car = Car("Ford", "Mustang", 2022)
print(my_car.get_make())
print(my_car.get_model())
print(my_car.get_year())
In this example, we define a class named Car. It has three attributes: make, model, and year. The __init__ method is the constructor that initializes the attributes when an object of the class is created. The get_make, get_model, and get_year methods are instance methods that return the values of the attributes of the object.
To create an instance of the Car class, we can use the following code:
my_car = Car("Toyota", "Corolla", 2022)
This creates an object of the Car class with the make attribute set to "Toyota", the model attribute set to "Corolla", and the year attribute set to 2022. We can access the attributes of the object using the dot notation:
print(my_car.make) # output: Toyota
print(my_car.model) # output: Corolla
print(my_car.year) # output: 2022
We can also call the instance methods of the object:
print(my_car.get_make()) # output: Toyota
print(my_car.get_model()) # output: Corolla
print(my_car.get_year()) # output: 2022