Python Object-Oriented Programming(OOP)
What is Object-Oriented Programming(OOP)?
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, that are times of instructions.
It is primarily based on the ideas of encapsulation, inheritance, and polymorphism.
Class and Object:
Class is a blueprint for growing object (instances). It defines the properties (attributes) and behaviors (methods) that objects of the class may have.
Classes are created using the class keyword observed by using the class name and a colon, observed by the class body, which includes elegance attributes and objects.
A class is a blueprint for creating objects, and an object is an instance of a class.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
- The Dog class has an __init__ method (a constructor) that initializes the object's attributes.
- The bark method is a behavior associated with the Dog class.
Creating Objects:
Creating objects, also known as instances, involves instantiating a class to create a concrete realization of that class.
Once a class is defined, you can create multiple objects (instances) of that class, each with its own set of attributes and behaviors.
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
print(dog1.name) # Output: Buddy
print(dog2.age) # Output: 5
dog1.bark() # Output: Buddy says Woof!
You create instances (objects) of the Dog class and access their attributes and methods.
Inheritance:
Inheritance is a effective feature of object-orientated programming (OOP) that lets in a class (called the child or derived class) to inherit attributes and methods from every other elegance (called the parent or base class). The child magnificence can then increase or modify the behavior of the discern elegance with the aid of including new attributes or techniques, or with the aid of overriding current ones.
The child class inherits all the attributes and methods of the discern magnificence without needing to redefine them. This promotes code reuse and enables in organizing training in a hierarchical structure based totally on their similarities and differences.
To implement inheritance in Python, you define a new class and specify the parent class(es) from which it should inherit by including them in parentheses after the class name.
Inheritance allows a class to inherit attributes and methods from another class.
class Cat(Dog):
def purr(self):
print(f"{self.name} says Purr!")
cat1 = Cat("Whiskers", 2)
cat1.bark() # Inherits the bark method from the Dog class
cat1.purr() # New method specific to the Cat class
Encapsulation:
Encapsulation is the process of bundling the data (attributes) and methods (functions) that perform on the data within a unmarried unit, referred to as a category. It hides the internal state of an object from the out of doors world and most effective exposes a managed interface for interacting with the object. Encapsulation lets in for records abstraction, because of this that the implementation info of a category are hidden from the consumer of the class.
Encapsulation is achieved by using access modifiers to control the visibility of class members. In Python, access modifiers are implemented through naming conventions rather than through keywords like in some other programming languages.
Encapsulation is the bundling of data (attributes) and methods that operate on that data within a single unit (class).
There are three levels of access control for class members in Python:
- Public: Members (attributes and methods) are accessible from outside the class. By default, all members in a Python class are public.
- Protected: Members are accessible within the class and its subclasses (inheritors), but not from outside. In Python, a member is conventionally marked as protected by prefixing its name with a single underscore (_).
- Private: Members are accessible only within the class itself. In Python, a member is conventionally marked as private by prefixing its name with a double underscore (__).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if amount > 0 and amount <= self.__balance:
self.__balance -= amount
def get_balance(self):
return self.__balance
The __balance attribute is private, and it can only be accessed and modified through the methods of the class.
Polymorphism:
Polymorphism in Python refers to the ability of different objects to respond to the same message or method call in different ways. It allows objects of different classes to be treated as objects of a common superclass. This enables a single interface to be used for entities of different types, providing flexibility and code reuse.
There are two main types of polymorphism in Python:
- Overloading: Involves defining multiple methods with the same name but with different parameters or argument types within a single class. The appropriate method is selected based on the number and types of arguments passed to it.
- Overriding: Occurs when a method in a subclass has the same name and signature (i.e., the same method name and parameters) as a method in its superclass. The method in the subclass overrides the implementation of the method in the superclass, allowing the subclass to provide its own implementation.
Polymorphism allows objects of different classes to be treated as objects of a common base class.
def introduce(animal):
animal.bark()
dog = Dog("Buddy", 3)
cat = Cat("Whiskers", 2)
introduce(dog) # Output: Buddy says Woof!
introduce(cat) # Output: Whiskers says Woof! (inherits bark method from Dog)
The introduce function takes any object with a bark method, demonstrating polymorphism.
Class and Instance Variables:
Class variables and instance variables are two types of variables that can be defined within a class.
class Circle:
pi = 3.14159 # Class variable
def __init__(self, radius):
self.radius = radius # Instance variable
def area(self):
return Circle.pi * self.radius**2
circle1 = Circle(5)
circle2 = Circle(7)
print(circle1.area()) # Output: 78.53975
print(circle2.area()) # Output: 153.93804
pi is a category variable shared by using all times, and radius is an instance variable precise to each item.
Object-Oriented Programming is an technique which encapsulates the concrete hassle location items and their relationships in a more herbal and express manner. It achieves the code reusability, modularity and higher shape.