Object-oriented programming (OOP) is a programming paradigm that allows you to organize code into classes and objects. Python fully supports OOP and allows you to create classes, define methods, and create objects from those classes.
Classes and Objects
A class is a blueprint for creating objects. It defines properties (attributes) and behaviors (methods) that all objects of that class will have. Here’s an example of a simple class:
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 am", self.age, "years old.")
You can create objects (instances) of a class like this:
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
You can then access the properties and call the methods of these objects like this:
print(person1.name)
# Output: Alice
print(person2.age)
# Output: 25
person1.greet()
# Output: Hello, my name is Alice and I am 30 years old.
person2.greet()
# Output: Hello, my name is Bob and I am 25 years old.
Inheritance
Inheritance is a feature of OOP that allows a class to inherit properties and methods from another class. The class that inherits is called the subclass, and the class that is inherited from is called the superclass. Here’s an example:
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def display_grade(self):
print("My grade is", self.grade)
In this example, the Student
class inherits from the Person
class.
Understanding object-oriented programming is essential for writing modular and maintainable Python code. In the next chapter, we’ll explore working with libraries and packages, which allow you to extend the functionality of Python.