In Python, a class is a blueprint for creating objects (a particular data structure). It defines a set of attributes and methods that characterize any object of the class.
# Defining a basic class
class Dog:
def __init__(self, name, age): # The __init__ method initializes object attributes
self.name = name # Attribute
self.age = age # Attribute
# Creating an object (instance) of the Dog class
dog1 = Dog("Buddy", 5)
# Accessing attributes
print(dog1.name) # Output: Buddy
print(dog1.age) # Output: 5
Methods are functions defined inside a class that describe the behaviors of an object. Here’s an example where we add a bark
method to the Dog
class:
# Adding methods to a class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self): # Method
return "Woof!"
# Creating an object and calling its method
dog1 = Dog("Buddy", 5)
print(dog1.bark()) # Output: Woof!
__init__
Method (Constructor)The __init__
method is called a constructor. It is a special method that is automatically invoked when a new object of the class is created. It’s used to initialize the object’s attributes:
# The __init__ method (constructor) initializes object attributes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating a new Person object
person1 = Person("Alice", 30)
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
Inheritance allows a class to inherit attributes and methods from another class. Here, we have a base class Animal
and a derived class Cat
that inherits from it:
# Inheritance example
class Animal:
def __init__(self, name):
self.name = name
def speak(self): # Base method
return "Some sound"
class Cat(Animal): # Cat inherits from Animal
def speak(self): # Overriding the base method
return "Meow!"
# Creating an object of the Cat class
cat1 = Cat("Whiskers")
print(cat1.name) # Output: Whiskers
print(cat1.speak()) # Output: Meow!
Encapsulation is the practice of keeping certain data private within a class. Attributes prefixed with double underscores __
are treated as private and cannot be accessed directly from outside the class.
# Encapsulation in Python
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # Private attribute
def deposit(self, amount): # Method to modify private attribute
self.__balance += amount
def get_balance(self): # Getter method
return self.__balance
# Creating a BankAccount object
account = BankAccount()
account.deposit(100)
print(account.get_balance()) # Output: 100
Use the interactive editor below to try out Python code:
« Previous Next »