This document presents a detailed working Python code sample that demonstrates the use of constructors, class variables, and instance variables. These three components are fundamental to object-oriented programming (OOP) in Python. Understanding how they work together allows developers to build scalable, readable, and maintainable applications.
We will explain the concept behind each component and then implement a sample application that demonstrates their interactions. The code is fully annotated and explained in a step-by-step manner.
The constructor is a special method used to initialize new objects. It is automatically called when a new instance of a class is created. It typically sets up instance variables.
Instance variables are data members that are specific to each object. They are usually defined inside the constructor and prefixed with self.
Class variables are shared among all instances of a class. They are defined inside the class but outside of any methods. They are useful for keeping track of common data shared across instances, like a counter for how many instances have been created.
In our working code sample, we will develop a simple Library Management System. This system will allow us to:
class Book:
# Class variable
total_books = 0
# Constructor with instance variables
def __init__(self, title, author, genre):
self.title = title # Instance variable
self.author = author # Instance variable
self.genre = genre # Instance variable
Book.total_books += 1 # Modify class variable
Hereβs what happens:
def display_info(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Genre: {self.genre}")
@classmethod
def display_total_books(cls):
print(f"Total books in library: {cls.total_books}")
Using @classmethod allows us to access the class variable total_books without referring to a specific instance.
class Book:
total_books = 0 # Class variable
def __init__(self, title, author, genre):
self.title = title # Instance variable
self.author = author # Instance variable
self.genre = genre # Instance variable
Book.total_books += 1
def display_info(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Genre: {self.genre}")
print("----------")
@classmethod
def display_total_books(cls):
print(f"Total books in library: {cls.total_books}")
# Creating instances
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", "Fiction")
book2 = Book("A Brief History of Time", "Stephen Hawking", "Science")
book3 = Book("To Kill a Mockingbird", "Harper Lee", "Drama")
# Display individual book info
book1.display_info()
book2.display_info()
book3.display_info()
# Display total number of books
Book.display_total_books()
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Genre: Fiction
----------
Title: A Brief History of Time
Author: Stephen Hawking
Genre: Science
----------
Title: To Kill a Mockingbird
Author: Harper Lee
Genre: Drama
----------
Total books in library: 3
def update_info(self, title=None, author=None, genre=None):
if title:
self.title = title
if author:
self.author = author
if genre:
self.genre = genre
This allows modification of instance variables after object creation.
def __str__(self):
return f"{self.title} by {self.author} [{self.genre}]"
print(book1) # Output: The Great Gatsby by F. Scott Fitzgerald [Fiction]
Each object has its own memory for instance variables, but class variables are stored only once in memory, which saves resources when tracking common data across objects.
library = [book1, book2, book3]
for book in library:
print(book.title, "-", book.genre)
@staticmethod
def library_policy():
print("Books must be returned in 15 days.")
Static methods do not depend on instance or class state.
class Book:
total_books = 0 # Class variable
def __init__(self, title, author, genre):
self.title = title # Instance variable
self.author = author # Instance variable
self.genre = genre # Instance variable
Book.total_books += 1
def display_info(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Genre: {self.genre}")
print("----------")
def update_info(self, title=None, author=None, genre=None):
if title:
self.title = title
if author:
self.author = author
if genre:
self.genre = genre
@classmethod
def display_total_books(cls):
print(f"Total books in library: {cls.total_books}")
@staticmethod
def library_policy():
print("Books must be returned in 15 days.")
def __str__(self):
return f"{self.title} by {self.author} [{self.genre}]"
# Usage
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", "Fiction")
book2 = Book("A Brief History of Time", "Stephen Hawking", "Science")
book3 = Book("To Kill a Mockingbird", "Harper Lee", "Drama")
# Display all info
book1.display_info()
book2.display_info()
book3.display_info()
# Class method
Book.display_total_books()
# Static method
Book.library_policy()
# Update book info
book1.update_info(genre="Classic")
print(book1)
# Iterate through book list
library = [book1, book2, book3]
for b in library:
print(b)
Through this working code sample, weβve demonstrated how Python's constructor, instance variables, and class variables work in unison. The constructor ensures that each object starts with the correct data. Instance variables maintain individual states, while class variables keep track of shared data like a book count. With these concepts, developers can construct complex applications with clean, maintainable code structures using Python's object-oriented capabilities.
Such practices are invaluable not only in small scripts but also in large systems like web applications, APIs, games, or financial software. Understanding these fundamentals lays the foundation for mastering Python and software engineering as a whole.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved