Python Class and Object Tutorial
OOP, or Object-Oriented Programming in Python, is a programming paradigm that organizes code into objects, which are instances of classes. This approach makes it easier to structure complex programs, enabling code reuse and modularity.
In Python, a class is a blueprint for creating objects (specific instances of data). Classes bundle data and the methods that operate on that data in a single, cohesive unit. They are essential for object-oriented programming in Python, allowing you to model real-world entities and their interactions.
Defining a Class
You define a class in Python using the class keyword, followed by the class name and a colon. By convention, class names are written in Pascal Case.
Class is a blueprint for creating objects. It defines attributes (properties) and methods (functions) that the objects created from it will have.
class Person:
pass # An empty class; we can define attributes and methods later
Creating Objects (Instances)
An object is an instance of a class. You create an instance by calling the class name as if it were a function. Each object has its own state and behavior based on the class.
person1 = Person () # Creates an instance of the Person class
Attributes and Methods
Classes have attributes (variables) and methods (functions) associated with them. Attributes represent the data, and methods define the behavior.
1. Attributes
Attributes can be defined within methods or directly in the class body. The __init__ () method is a special constructor method called automatically when a new instance is created, and it’s typically used to initialize attributes.
class Person:
# Constructor method to initialize attributes
def __init__ (self, name, age):
self.name = name # instance attribute
self.age = age # instance attribute
# Creating an object with attributes
person1 = Person (“Alice”, 30)
print(person1.name) # Outputs: Alice
print(person1.age) # Outputs: 30
2. Methods
Methods are functions defined within a class that describe the behaviors of an object. The first parameter of a method is always self, which is a reference to the current instance.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def greet(self):
return f”Hello, my name is {self.name} and I am {self.age} years old.”
# Creating an object and calling its method
person1 = Person (“Alice”, 30)
print (person1.greet()) # Outputs: Hello, my name is Alice and I am 30 years old.
Types of Methods
- Instance methods: Operate on an instance. The first parameter is self.
- Class methods: Operate on the class itself. Defined with @classmethod and take cls as the first parameter.
- Static methods: Regular functions within a class. Defined with @staticmethod, they don’t take self or cls as the first parameter.
Example of Class and Static Methods
class Person:
species = “Homo sapiens” # Class attribute
def __init__ (self, name, age):
self.name = name
self.age = age
@classmethod
def species_info(cls):
return f”All people are of species: {cls. species}”
@staticmethod
def is_adult(age):
return age >= 18
# Accessing class method and static method
print (Person.species_info ()) # Outputs: All people are of species: Homo sapiens
print (Person.is_adult (20)) # Outputs: True
Inheritance
Inheritance allows a class to inherit attributes and methods from another class. The new class (child) inherits from an existing class (parent), promoting code reuse.
class Employee(Person): # Employee class inherits from Person
def __init__(self, name, age, position):
super().__init__(name, age) # Call the parent constructor
self.position = position
# Creating an instance of Employee
employee1 = Employee(“Bob”, 25, “Developer”)
print(employee1.greet()) # Outputs: Hello, my name is Bob and I am 25 years old.
print(employee1.position) # Outputs: Developer
Encapsulation and Access Modifiers
Encapsulation involves restricting access to certain attributes or methods. By convention:
- Attributes prefixed with _ are intended for internal use (protected).
- Attributes prefixed with __ make them harder to access from outside the class (private).
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
# Creating a bank account instance
account = BankAccount(“Alice”, 100)
account.deposit(50)
print(account.get_balance()) # Outputs: 150
Summary of Class Components
- Class definition: class ClassName:.
- Constructor: __init__() to initialize instance attributes.
- Instance methods: Define behaviors using self.
- Class methods: Defined with @classmethod, operate on cls.
- Static methods: Defined with @staticmethod, don’t access class/instance.
- Inheritance: Extend functionality of an existing class by inheriting it.
Classes in Python make it easy to structure complex code and model real-world entities with encapsulated data and behaviors.