Python

Simple Python Guide For Beginners

22 min read

Object-Oriented Programming

In this section, you will learn about object-oriented programming (OOP) in Python. OOP is a programming paradigm that allows you to structure your code around objects, which represent real-world entities. We will cover topics such as classes and objects, attributes and methods, inheritance, and encapsulation.

Classes and Objects

In Python, a class is a blueprint for creating objects. An object is an instance of a class. Here’s an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
Attributes and Methods

A class can have attributes (variables) and methods (functions). Attributes store data, while methods perform actions. Here’s an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print("Hello, my name is " + self.name + " and I'm " + str(self.age) + " years old.")

person = Person("Alice", 25)
person.greet()  # Output: Hello, my name is Alice and I'm 25 years old.
Inheritance

Inheritance allows you to create a new class (child class) based on an existing class (parent class). The child class inherits the attributes and methods of the parent class. Here’s an example:

class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(self.name + " is eating.")

class Dog(Animal):
    def bark(self):
        print("Woof!")

dog = Dog("Buddy")
dog.eat()   # Output: Buddy is eating.
dog.bark()  # Output: Woof!
Encapsulation

Encapsulation is the process of hiding internal details of a class and providing access to them through methods. It helps maintain data integrity and improves code maintainability. Here’s an example:

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance
    def deposit(self, amount):
        self.__balance += amount
    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient balance.")
    def get_balance(self):
        return self.__balance
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
balance = account.get_balance()
print(balance)  # Output: 1300


Content List