Kodeclik Blog
Making a class in Python
Python is a versatile language and provides capabilities for object-oriented programming. Creating classes and defining instances of classes is one of the main characteristics of object oriented programming.
What is a Class in Python?
In Python, a class is a blueprint for creating objects. It provides a way to bundle data (attributes) and functionality (methods) together.
The best way to understand classes and objects is to think of them as proper nouns and common nouns. For example, "Dog" is a class (a common noun), while "Buddy" is an object or instance of that class (a proper noun). Similarly, "Car" is a class, while "Toyota Corolla" is an instance of that class. Classes define the structure, behavior, and properties of objects, while objects are the specific instances created from those classes.
How do you Define a Class?
A class in Python serves as a schematic or blueprint for creating objects, which are instances of that class. Classes encapsulate data (attributes) and behaviors (methods), allowing programmers to model real-world entities in code.
A Python class definition defines attributes (variables) and methods (functions) that the objects created from the class will have. Classes are defined using the class keyword, and you can create instances (objects) of the class by calling it like a function.
Basic Syntax of a Class in Python
The basic syntax of a class in Python follows the below structure:
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
def method_name(self):
return f"Attributes: {self.attribute1}, {self.attribute2}"
The basic syntax of a class in Python provides a structured way to define objects. It starts with the class keyword followed by the class name in PascalCase. The __init__ method (constructor) initializes the attributes of the class when an instance is created. Attributes are defined using self, which refers to the instance itself. Methods, defined as functions within the class, allow interaction with these attributes or perform specific actions. This structure enables encapsulation of data and behavior into reusable blueprints that can be instantiated multiple times.
Now let us see some examples.
Example 1: Car Class
Consider the Car class definition:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def description(self):
return f"{self.year} {self.make} {self.model}"
# Create an instance
my_car = Car("Toyota", "Corolla", 2020)
print(my_car.description()) # Output: 2020 Toyota Corolla
The Car class demonstrates the basic structure of a Python class, including attributes and methods. In this example, the class has three attributes: make, model, and year, which are initialized through the constructor method __init__. This method is called automatically when an instance of the class is created, allowing the user to provide initial values for these attributes. The class also includes a method called description(), which returns a formatted string describing the car. This example introduces the concept of encapsulating data (attributes) and behavior (methods) within a class, making it easier to model real-world entities like cars in code.
Example 2: Student Class
The Student class introduces additional features such as unique identifiers for objects and methods that interact with attributes.
class Student:
def __init__(self, sid, name, gender):
self.sid = sid
self.name = name
self.gender = gender
def introduce(self):
return f"My name is {self.name}, ID: {self.sid}, Gender: {self.gender}"
# Create an instance
student1 = Student("001", "Alice", "Female")
print(student1.introduce()) # Output: My name is Alice, ID: 001, Gender: Female
The attributes sid (student ID), name, and gender are initialized using the constructor __init__. The method introduce() demonstrates how a class can define behaviors that use its attributes, returning a formatted string to introduce the student. This example highlights how classes can be used to represent individuals or entities with specific properties and behaviors, making them useful for applications like school management systems or personal data tracking.
Example 3: BankAccount Class
Now we get to a more complicated class definition. The BankAccount class introduces private attributes and methods for manipulating data, showcasing basic encapsulation.
class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return amount
else:
return "Insufficient funds"
# Create an instance
account = BankAccount(12345)
account.deposit(500)
print(account.withdraw(200)) # Output: 200
print(account.withdraw(400)) # Output: Insufficient funds
The attribute balance is initialized with a default value of 0, and methods like deposit() and withdraw() allow controlled access to modify this balance. The withdrawal method includes logic to check if sufficient funds are available before deducting from the balance, demonstrating how classes can enforce rules and constraints on their data. This example illustrates how classes can model systems with state management and business logic, such as banking applications where security and correctness are critical.
Example 4: Book Class
Finally, the Book class introduces boolean attributes and methods for updating state, showcasing how classes can represent objects with dynamic properties.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
self.read = False
def mark_as_read(self):
self.read = True
# Create an instance
my_book = Book("1984", "George Orwell", 328)
print(f"Title: {my_book.title}, Read: {my_book.read}") # Output: Title: 1984, Read: False
my_book.mark_as_read()
print(f"Read status after marking as read: {my_book.read}") # Output: Read status after marking as read: True
The above class definition includes attributes like title, author, and pages, along with a boolean attribute read that tracks whether the book has been read. The method mark_as_read() allows users to update the state of the book by setting the read attribute to True. This example demonstrates how classes can model objects with changing states over time, making them ideal for applications like library systems or personal reading trackers where tracking progress is essential.
Conclusion
Classes are one of the most powerful features of Python, enabling developers to model real-world entities and systems efficiently. By encapsulating data (attributes) and behaviors (methods), classes provide a foundation for building scalable, maintainable, and reusable code.
Through examples like the Car, Student, BankAccount, and Book classes, we see how Python's object-oriented programming capabilities can be applied to solve practical problems across various domains. Whether you're managing data, enforcing rules, or tracking states, understanding how to create and use classes is essential for writing robust Python applications.
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.