Classes Objects in Python
? Classes and Objects in Python
In Python, classes and objects are the building blocks of Object-Oriented Programming (OOP). A class defines the blueprint for creating objects (instances), and an object is an instance of a class.
? Class
A class is a template for creating objects. It encapsulates data and methods that operate on the data.
class Car: # Constructor (initializer) def __init__(self, make, model, year): self.make = make # Instance variable self.model = model # Instance variable self.year = year # Instance variable # Method def display_info(self): return f"{self.year} {self.make} {self.model}"__init__: The constructor method initializes the instance variables when the object is created.self: Refers to the current instance of the class.
? Creating an Object
You create an object by calling the class as if it were a function.
# Creating an object (instance) of the Car classmy_car = Car("Toyota", "Corolla", 2022)# Accessing object's attributesprint(my_car.make) # Output: Toyotaprint(my_car.model) # Output: Corollaprint(my_car.year) # Output: 2022# Calling a methodprint(my_car.display_info()) # Output: 2022 Toyota Corolla? Instance vs. Class Variables
Instance Variables: Unique to each object.
Class Variables: Shared by all objects of a class.
class Dog: species = "Canine" # Class variable def __init__(self, name, breed): self.name = name # Instance variable self.breed = breed # Instance variable# Creating objectsdog1 = Dog("Buddy", "Golden Retriever")dog2 = Dog("Max", "Bulldog")# Accessing class variableprint(dog1.species) # Canineprint(dog2.species) # Canine# Accessing instance variablesprint(dog1.name) # Buddyprint(dog2.name) # Max? Methods and Self
Methods are functions defined inside a class that operate on the instance of the class.
selfis the reference to the current instance.
class Person: def __init__(self, name, age): self.name = name self.age = age # Method to display person's information def greet(self): return f"Hello, my name is {self.name} and I am {self.age} years old."# Creating an objectperson1 = Person("Alice", 30)# Calling the methodprint(person1.greet()) # Output: Hello, my name is Alice and I am 30 years old.? Inheritance
Inheritance allows one class to inherit attributes and methods from another class. This promotes code reusability.
class Animal: def __init__(self, name): self.name = name def speak(self): return "Animal sound"# Dog inherits from Animalclass Dog(Animal): def speak(self): return "Woof"# Creating an object of Dog classdog = Dog("Buddy")print(dog.name) # Buddy (inherited from Animal)print(dog.speak()) # Woof (Overridden method in Dog class)? Encapsulation
Encapsulation refers to bundling data (attributes) and methods that operate on the data into a single unit, or class. It also involves restricting access to certain methods and attributes by using private and public access modifiers.
class Account: def __init__(self, balance): self.__balance = balance # Private variable def deposit(self, amount): self.__balance += amount def withdraw(self, amount): if amount <= self.__balance: self.__balance -= amount else: print("Insufficient funds!") def get_balance(self): return self.__balance# Creating an objectacc = Account(1000)# Accessing and modifying balance using methodsacc.deposit(500)print(acc.get_balance()) # Output: 1500# Trying to access private variable directly (will cause error)# print(acc.__balance) # AttributeError: 'Account' object has no attribute '__balance'? Summary of Key Concepts:
Class: Blueprint to create objects.
Object: Instance of a class.
Constructor (
__init__): Initializes the object’s attributes.Methods: Functions defined inside a class that can operate on objects.
Inheritance: Allows one class to inherit from another.
Encapsulation: Restricts access to certain parts of an object’s data (using private and public members).
Let me know if you want to dive deeper into any of these concepts! ?