Loading...
Loading...

Object-Oriented Programming in Python

Object-Oriented Programming (OOP) in Python provides a way to organize code by grouping related data and functions into classes. Key concepts include classes, inheritance, and polymorphism.

1. What is a Class?

A class is a blueprint for creating objects. Each object created from a class is called an instance, containing its own data and methods.

Creating a Class

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

    def bark(self):
        return "Woof!"

Here, Dog is a class with an initializer method __init__ and a method bark(). The self parameter refers to the instance.

Creating an Instance

dog1 = Dog("Buddy", 3)
print(dog1.name)  # Output: Buddy
print(dog1.bark())  # Output: Woof!

Classes Quiz

What is the purpose of the __init__ method?

  • To destroy the object
  • To initialize the object's attributes
  • To print the object's details

What does self refer to in a class method?

  • The class itself
  • The instance of the class
  • The parent class

2. Inheritance

Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse and creating a hierarchy of classes.

Example of Inheritance

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

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

Here, Dog inherits from Animal, meaning it has access to the name attribute defined in Animal.

Using the Inherited Class

dog1 = Dog("Buddy")
print(dog1.name)  # Output: Buddy
print(dog1.bark())  # Output: Woof!

Inheritance Quiz

What is the main benefit of inheritance?

  • It makes code run faster
  • It promotes code reuse
  • It reduces the number of variables

How do you indicate a class inherits from another class?

  • Using the extends keyword
  • By putting the parent class in parentheses
  • With the inherits decorator

3. Polymorphism

Polymorphism allows different classes to be treated as instances of the same class through shared methods, promoting flexibility in code.

Example of Polymorphism

class Cat:
    def speak(self):
        return "Meow!"

class Dog:
    def speak(self):
        return "Woof!"

def make_animal_speak(animal):
    print(animal.speak())

Both Cat and Dog have a speak() method, allowing make_animal_speak() to call speak() on any object passed to it:

dog = Dog()
cat = Cat()
make_animal_speak(dog)  # Output: Woof!
make_animal_speak(cat)  # Output: Meow!

Polymorphism Quiz

What is the key requirement for polymorphism to work?

  • Classes must have the same attributes
  • Objects must share a common interface (method names)
  • Classes must inherit from the same parent

What is the output if we add make_animal_speak(5)?

  • AttributeError (no speak method)
  • "5"
  • Nothing (silently fails)

4. Encapsulation

Encapsulation restricts access to specific parts of an object, using private methods and variables to protect the internal state.

Example of Encapsulation

class BankAccount:
    def __init__(self, balance=0):
        self.__balance = balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def get_balance(self):
        return self.__balance

Here, __balance is a private variable, only accessible within the class through the get_balance() method.

Encapsulation Quiz

How do you indicate a private variable in Python?

  • Using the private keyword
  • Prefixing with double underscore (__)
  • Putting it in parentheses

What is the main purpose of encapsulation?

  • To make code run faster
  • To protect an object's internal state
  • To reduce the number of methods
0 Interaction
706 Views
Views
40 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home