Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to model real-world entities. Python supports OOP by allowing you to define classes and create objects.
Classes and Objects:
- Class: A blueprint for creating objects (defines attributes and methods).
- Object: An instance of a class.
Defining a Class:
class Dog:
"""A simple class to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate the dog sitting."""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""Simulate rolling over."""
print(f"{self.name} rolled over!")
Creating Objects:
my_dog = Dog("Buddy", 3)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()
my_dog.roll_over()
Inheritance:
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class).
Example:
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
class Cat(Animal):
def meow(self):
print(f"{self.name} says meow.")
my_cat = Cat("Whiskers")
my_cat.eat() # Inherited from Animal
my_cat.meow() # Defined in Cat