Objective: To understand the concept of Object-Oriented Programming (OOP) in Python by implementing a simple class Student and exploring its attributes and methods.
Theory: In Python, a class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the behavior of the object.
Class and Object:
A class is a template for creating objects.
An object is an instance of a class.
Constructor (__init__ method):
A special method that initializes the object's attributes.
Instance Variables:
Variables that belong to a specific object.
Class Variables:
Variables shared among all instances of a class.
Methods:
Functions defined within a class that operate on the class’s attributes.
Encapsulation:
Restricting direct access to some of an object's components.
Code Implementation:
class Student:
num = 0 # Class variable to count the number of students
""" Class representing a student """
def __init__(self, n, a):
self.name = n # Instance variable for student name
self.age = a # Instance variable for student age
self.__class__.num += 1 # Increments class variable num
def getAge(self):
return self.age # Getter method for age
def setAge(self, a):
self.age = a # Setter method for age
def __repr__(self):
return "I am " + self.name + " and I am a student" # String representation of the object
# Creating an object of the Student class
a = Student("Ali", 19)
# Accessing attributes and methods
print(a.age) # Output: 19
print(a.getAge()) # Output: 19
print(a.name) # Output: Ali
print(a) # Output: I am Ali and I am a student
Explanation:
A class Student is defined with a class variable num that counts the number of instances created.
The __init__ method initializes the name and age attributes.
getAge() and setAge() methods allow getting and setting the age attribute, respectively.
The __repr__ method returns a string representation of the object.
An object a is created, and its attributes/methods are accessed using print().
Expected Output:
19
19
Ali
I am Ali and I am a student
Exercises:
Create another Student object and check if num is updated correctly.
Modify the setAge() method to prevent setting a negative age.
Add a method getStudentCount() to return the number of students created.
Experiment by creating multiple objects and accessing their attributes.
Conclusion: By executing the above code, students will understand how to define and use classes in Python, work with instance and class variables, and implement encapsulation using getter and setter methods. This lab provides a fundamental understanding of OOP principles.