Mastering Object-Oriented Concepts in Python

Object-Oriented Programming (OOP) in Python is a programming paradigm that uses “objects” and their interactions to design applications and computer programs. It’s a way to structure and organize your code. Let’s dive into the core concepts of OOP in Python with examples:



Classes and Objects

Classes: Think of a class as a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).

Objects: An instance of a class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
return "Woof!"

# Create an instance of Dog
my_dog = Dog("Buddy", 3)
print(my_dog.bark()) # Outputs: Woof!



Inheritance:
  • It allows new objects to take on the properties of existing objects.
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

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

my_cat = Cat("Whiskers")
print(my_cat.speak()) # Outputs: Meow



Encapsulation:
  • The bundling of data, and the methods that operate on that data, into a single unit.
class Computer:
def __init__(self):
self.__max_price = 900 # private variable

def sell(self):
return f"Selling Price: {self.__max_price}"

def set_max_price(self, price):
self.__max_price = price

c = Computer()
print(c.sell()) # Outputs: Selling Price: 900

# Change the price
c.set_max_price(1000)
print(c.sell()) # Outputs: Selling Price: 1000




Polymorphism:
  • The ability to present the same interface for differing underlying data types.
class Parrot:
def fly(self):
return "Parrot can fly"

def swim(self):
return "Parrot can't swim"

class Penguin:
def fly(self):
return "Penguin can't fly"

def swim(self):
return "Penguin can swim"

# common interface
def flying_test(bird):
return bird.fly()

# instances
parrot = Parrot()
penguin = Penguin()

print(flying_test(parrot)) # Outputs: Parrot can fly
print(flying_test(penguin)) # Outputs: Penguin can't fly



Method Overriding:
  • It’s when a method in a subclass uses the same name as a method in its superclass but provides a specific implementation for it.
class Parent:
def myMethod(self):
return "Calling parent method"

class Child(Parent):
def myMethod(self):
return "Calling child method"

c = Child()
print(c.myMethod()) # Outputs: Calling child method

Apart from the core OOP concepts, there are several other useful concepts in Python programming that enhance the way we work with classes and objects. Here are some of them, along



Class Variables and Instance Variables 
  • Class Variables: Shared among all instances of a class.
  • Instance Variables: Unique to each instance.
class Employee:
# Class variable
raise_amount = 1.04

def __init__(self, first, last, pay):
# Instance variables
self.first = first
self.last = last
self.pay = pay

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)

emp1 = Employee('John', 'Doe', 50000)
emp2 = Employee('Jane', 'Doe', 60000)

# Apply raise
emp1.apply_raise()
print(emp1.pay) # Outputs: 52000



Static Methods and Class Methods
  • Static Methods: Behave like plain functions but belong to the class’s namespace.
  • Class Methods: Work with the class since its parameter is always the class itself.
class MyClass:
@staticmethod
def my_static_method():
return "This is a static method"

@classmethod
def my_class_method(cls):
return f"This is a class method of {cls}"

print(MyClass.my_static_method()) # Outputs: This is a static method
print(MyClass.my_class_method()) # Outputs: This is a class method of <class '__main__.MyClass'>



Property Decorators — Getters, Setters, and Deleters
  • Used to get, set, and delete the value of a property using methods as if they were attributes.
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

@property
def email(self):
return f"{@email.com">self.first_name}.{self.last_name}@email.com"

@property
def fullname(self):
return f"{self.first_name} {self.last_name}"

@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first_name = first
self.last_name = last

person = Person("John", "Smith")
person.fullname = "Corey Schafer"
print(person.first_name) # Outputs: Corey
print(person.email) # Outputs: Corey.Schafer@email.com




Magic/Dunder Methods


  • Special methods which have double underscores (dunder) at the beginning and the end of their names. They are used for operator overloading and customizing the behavior of Python classes.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages

def __str__(self):
return f"{self.title} by {self.author}"

def __len__(self):
return self.pages

book = Book("Python Programming", "John Doe", 300)
print(book) # Outputs: Python Programming by John Doe
print(len(book)) # Outputs: 300




Iterators and Generators
  • Iterators are objects that can be iterated upon. Generators yield a sequence of values lazily, pausing after each one until the next one is requested.
def countdown(num):
while num > 0:
yield num
num -= 1

for count in countdown(5):
print(count)
# Outputs: 5 4 3 2 1

10 multiple-choice questions (MCQs) to test your understanding of mastering object-oriented concepts in Python:


1. Which keyword is used to define a class in Python?
   a) class
   b) def
   c) obj
   d) Class

Correct Answer: a) class


2. What is encapsulation in object-oriented programming?
   a) Inheriting attributes and methods from another class
   b) Grouping data and methods that operate on the data within a single unit
   c) Creating multiple methods with the same name but different parameters
   d) Using objects of different classes interchangeably

Correct Answer: b) Grouping data and methods that operate on the data within a single unit


3. Which keyword is used to create an instance (object) of a class in Python?
   a) instance
   b) new
   c) obj
   d) None of the above

Correct Answer: d) None of the above (Objects are created using the class name followed by parentheses.)


4. What is inheritance in Python?
   a) A way to control access to class members
   b) Defining multiple methods with the same name but different parameters
   c) Bundling data and methods within a single unit
   d) Allowing a class to inherit attributes and methods from another class

Correct Answer: d) Allowing a class to inherit attributes and methods from another class


5. Which method is used for initializing object attributes in a class?
   a) init()
   b) constructor()
   c) __init__()
   d) initialize()

Correct Answer: c) __init__()


6. What does the `super()` function do in Python?
   a) Calls a method from the superclass
   b) Initializes object attributes
   c) Creates a new instance of a class
   d) Defines static methods

Correct Answer: a) Calls a method from the superclass


7. Which concept in object-oriented programming allows objects of different classes to be treated as objects of a common superclass?
   a) Polymorphism
   b) Encapsulation
   c) Inheritance
   d) Composition

Correct Answer: a) Polymorphism


8. What is the purpose of method overriding in Python?
   a) Controlling access to class members
   b) Customizing behavior in subclasses
   c) Defining multiple methods with the same name but different parameters
   d) Grouping data and methods within a single unit

Correct Answer: b) Customizing behavior in subclasses


9. Which type of method in Python is bound to the class rather than an instance?
   a) Instance method
   b) Static method
   c) Class method
   d) Dunder method

Correct Answer: c) Class method


10. What do decorators like `@property` and `@classmethod` enable in Python?
    a) Defining getter and setter methods
    b) Grouping data and methods within a single unit
    c) Controlling access to class members
    d) Defining multiple methods with the same name but different parameters

Correct Answer: a) Defining getter and setter methods







Comments

Popular posts from this blog

A Brief History of the Python Programming Language.

Understanding python Code Structure and Building Simple python Programs