Python Classes/Objects
In Python, classes and objects are fundamental concepts in object-oriented programming (OOP). A class is a blueprint for creating objects (instances), and an object is an instance of a class. Classes help in organizing code by bundling related data and functionality together. This is a core concept in many modern programming languages.
1. Defining a Class
A class is defined using the class keyword followed by the class name. A class can contain methods (functions) and attributes (variables) that define the behavior and characteristics of the objects created from the class.
Syntax:
class ClassName:
# Constructor method (special method __init__)
def __init__(self, parameters):
# Initialize object attributes
self.attribute1 = value
self.attribute2 = value
# Regular method
def method_name(self):
# Method functionality
2. Creating an Object
Once a class is defined, you can create objects (instances) of that class. The object is created by calling the class like a function, passing arguments to the __init__ method (constructor).
Example of a Simple Class:
class Person:
# Constructor to initialize object attributes
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
# Method to display person's details
def introduce(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create an object (instance) of the Person class
person1 = Person("Alice", 30)
# Accessing object attributes
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
# Calling an object method
person1.introduce() # Output: Hello, my name is Alice and I am 30 years old.
3. The __init__ Method (Constructor)
The __init__ method is a special method in Python that is automatically called when a new object (instance) of the class is created. It is used to initialize the attributes of the object.
Example:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# Create an object
my_car = Car("Toyota", "Corolla", 2020)
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
In this example, the __init__ method initializes the make, model, and year attributes of the Car object.
4. Methods in a Class
A method is a function that belongs to a class. It is defined using the def keyword and must always have self as the first parameter. The self parameter allows the method to access the instance’s attributes and other methods.
Example:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
# Create an object
dog1 = Dog("Buddy", "Golden Retriever")
# Calling a method
dog1.bark() # Output: Buddy says Woof!
5. Accessing Attributes and Methods
You can access the attributes and methods of an object using dot notation (.).
Example:
# Accessing an attribute
print(dog1.name) # Output: Buddy
# Calling a method
dog1.bark() # Output: Buddy says Woof!
6. Instance vs. Class Variables
- Instance variables are attributes that are specific to each instance of the class. They are defined in the
__init__method usingself. - Class variables are shared by all instances of the class. They are defined directly within the class.
Example with Class and Instance Variables:
class Animal:
# Class variable
species = "Canine"
def __init__(self, name):
# Instance variable
self.name = name
# Create objects
dog1 = Animal("Buddy")
dog2 = Animal("Bella")
# Access instance variables
print(dog1.name) # Output: Buddy
print(dog2.name) # Output: Bella
# Access class variable
print(dog1.species) # Output: Canine
print(dog2.species) # Output: Canine
# Changing class variable
Animal.species = "Feline"
print(dog1.species) # Output: Feline
print(dog2.species) # Output: Feline
7. Inheritance
Inheritance allows one class (the child class) to inherit the attributes and methods of another class (the parent class). This helps in reusing code and extending functionality.
Syntax of Inheritance:
class ChildClass(ParentClass):
def __init__(self, parameters):
super().__init__(parameters) # Calls the parent class's __init__ method
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling the parent class's constructor
self.breed = breed
def speak(self):
print(f"{self.name} barks!")
# Create objects
dog1 = Dog("Buddy", "Golden Retriever")
dog1.speak() # Output: Buddy barks!
In this example, the Dog class inherits from the Animal class and overrides the speak method to provide a specific implementation for dogs.
8. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common base class. The most common use of polymorphism is when different classes implement the same method in different ways.
Example:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
# Create objects
animals = [Dog(), Cat()]
# Calling the same method on different objects
for animal in animals:
animal.speak()
Output:
Dog barks
Cat meows
In this example, both the Dog and Cat classes override the speak method, and Python calls the appropriate method based on the object type.
9. Encapsulation
Encapsulation is the practice of keeping fields (attributes) private, only allowing access via methods (getters and setters). In Python, this is typically achieved by prefixing attributes with an underscore (_) or double underscore (__).
Example of Encapsulation:
class Person:
def __init__(self, name, age):
self._name = name # Protected attribute
self.__age = age # Private attribute
def get_age(self):
return self.__age
def set_age(self, age):
if age >= 0:
self.__age = age
else:
print("Age cannot be negative")
person = Person("John", 25)
print(person.get_age()) # Output: 25
# Trying to access private attribute directly will raise an error
# print(person.__age) # AttributeError: 'Person' object has no attribute '__age'
person.set_age(30)
print(person.get_age()) # Output: 30
10. Destructors
A destructor is a special method called when an object is destroyed. In Python, the destructor method is __del__.
Example of Destructor:
class MyClass:
def __init__(self, name):
self.name = name
print(f"Object {self.name} created")
def __del__(self):
print(f"Object {self.name} destroyed")
obj = MyClass("Test Object")
del obj # Manually destroy the object
Output:
Object Test Object created
Object Test Object destroyed
Summary of Classes/Objects in Python:
- Class: A blueprint for creating objects, defining attributes and methods.
- Object: An instance of a class that has attributes and behaviors.
- Constructor (
__init__): A special method that initializes the object’s attributes. - Methods: Functions defined within a class that describe the behaviors of the object.
- Inheritance: A mechanism to create a new class from an existing class, inheriting its properties and methods.
- Polymorphism: The ability of different classes to be treated as instances of the same class, allowing different implementations of the same method.
- Encapsulation: The practice of restricting access to certain attributes or methods to ensure they are used correctly.
- Destructor (
__del__): A method that is automatically called when an object is destroyed.