Classes and Objects in Python
Classes and objects are the foundation of object-oriented programming in Python. A class is a blueprint for creating objects, and an object is an instance of a class.
Defining a Class
Classes in Python are defined using the class
keyword. The __init__
method is used to initialize object attributes.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark() # Output: Woof!
Class Attributes
Class attributes are shared by all instances of a class. They are defined outside of any method.
class Dog:
species = "Canis familiaris" # Class attribute
def __init__(self, name, breed):
self.name = name
self.breed = breed
print(Dog.species) # Output: Canis familiaris
Static Methods
Static methods are methods that belong to the class rather than an instance. They do not have access to self
or cls
.
class Math:
@staticmethod
def add(x, y):
return x + y
result = Math.add(5, 10)
print(result) # Output: 15
Class Methods
Class methods are methods that operate on the class itself rather than an instance. They take cls
as the first parameter.
class Dog:
species = "Canis familiaris"
@classmethod
def get_species(cls):
return cls.species
print(Dog.get_species()) # Output: Canis familiaris
Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def speak(self):
print("Animal sound")
class Cat(Animal):
def speak(self):
print("Meow")
my_cat = Cat()
my_cat.speak() # Output: Meow
Encapsulation
Encapsulation is the concept of restricting access to certain attributes or methods. In Python, this is achieved using private attributes (prefixed with __
).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
class Dog:
def speak(self):
print("Woof!")
class Cat:
def speak(self):
print("Meow")
def animal_sound(animal):
animal.speak()
dog = Dog()
cat = Cat()
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow
Back to Tutorial