Python Programming – The Class Program

The complete program representing the entire concept of creating classes and objects is given in Code 10.4. Here we see that a class variable student is created and two data members i.e., name and roll no are created. The values to name and roll are assigned through the constructor method __init__( ) in Python. It contains three arguments. The first is the self, which is mandatory in Python for every function (method) to be used within the class. The other two arguments are name and roll no.

Two class methods display count() and display student() is also defined to display the total number of students and information of the students. Then, two objects soul and stu2 and created with the values of name and roll no, which are passed as arguments to the constructor function. Subsequently, the display student() method is called through stu1 and stu2 objects by using the dot(.) operator. The value of the common class variable stuCount is displayed or accessed by using the class name with the variable name student along with dot operator. The output of this code explains it all.

Code: 10.4, Illustration of using classes and objects in Python.

#illustration of creating a class in Python

class Student:
‘A student class’
stuCount = 0

def init (self, name, rollno): #initialization or constructor method of
#class Student
selfname = name
selfrollno = rollno
Student.stuCount += 1

def displayCount(self): #displayCount method of class Student
print (“Total Students %d”, Student.stuCount)

def displayStudent(self): #displayStduent method of class
#Student
print (“Name : “, self.name, ” Rollno: “, self.rollno)

stu1=Student(‘John’, 111)
stu2=Student(‘Clara’, 112)
stul.displayStudent()
stu2.displayStudent()
print(‘total no. of students:’, Student.stuCount)

Output

Name : John, Rollno: 111
Name: Clara,Rollno: 112
total no. of students: 2

Using a Class with Input

In the above program, we have seen that the init () method is used as a constructor to pass values to the class attributes name and roll no. What if the user wishes to give his/her input for the attributes? In order to understand this concept, consider a program given in Code 10.5. for the same class Student.

Code: 10.5. Illustration of class with input from the user.

#illustration of creating a class in Python with input from the user

class Student:
‘A student class’
stuCount = 0
def init (self): initialization or constructor method of
#class Student
self.name=input(‘enter student name:’)
self.rollno=input(’enter student rollno:’)
Student. stuCount += 1

def displayStudent(self): #displayStduent method of class Student print (“Name :”, self.name, “, Rollno:”, self.rollno)

stu1=Student()
stu2=Student()
stu3=Student()
stul.displayStudent()
stu2.displayStudent()
stu3.displayStudent() .
print(‘total no. of students:’, Student.stuCount)

Output

enter student name:John
enter student rollno:21
enter student name:Clara
enter student rollno: 122
enter student name:Richie
enter student rollno: 123
Name :John, Rollno: 121
Name : Clara, Rollno: 122
Name : Richie , Rollno: 123
total no. of students: 3

It is to be noted that while using class in Python, the init () method is mandatory to be called for declaring the class data members, without which we can not declare the instance variables(data members) for the objects of the class. A variable declared outside the init () method are termed a class variable such as the student variable in the above program. It is to be noted that the class variables are accessed as className.class variable name, e.g. Student. student in the above program. However, the instance variables or data members are accessed as self. instance variable name, e.g., self. Name in the above program 10.5.

In this program, we see that the input() function is called in the definition of __init__() method for inputting the values of data variables name and rollno. Subsequently, the value of stuCount is incremented by 1 in order to keep track of the total number of objects created for the class Student. In this program, three objects stul, stu2, and stu3 are created thereby calling the constructor function init () three times. The values are assigned to name and rollno after input from the user. Then, the result is displayed by calling the displayed student() function of class Student. The output of this program can be referred to for more lucidity.

A Class Program with Computations

Here, we present another program using the concept of class and objects. We create a class inventory and compute the total price of each item along with the total bill of all the purchased items. The programming example for this problem is given in Code 10.6.

Code: 10.6. Managing inventory using classes.

#illustration of creating and handling Inventory using class

class Inventory:
‘An inventory class’
itemCount = 0
total_bill = 0

def init (self, item, price, quantity):     #constructor method of
#class Inventory
self.item = item
self.price = price
self.quantity = quantity
self.total = self.price*self.quantity
Inventory .total_bill += self.total
Inventory.itemCount += 1

def displayltem(self):                #displayStudent method of
#class Inventory
print (“\nItemName :”, self.item, “\nPrice:”, self.price, “\nQuantity: “, self.quantity, “\nTotal:”, self.total)

Il=Inventory(’Soap’, 30.5,4)
I2=Inventory(‘Shampoo’, 130.5, 2)
I3=Inventory(‘Oil’, 80.5, 1)
11. displayltem()
12. displayltem()
13. displayltem()
print(‘\ntotal no. of items:’, Inventory.itemCount)
print(‘\ntotal bill:’, Inventory.total bill)

Output

ItemName: Soap
Price: 30.5
Quantity: 4
Total: 122.0

ItemName: Shampoo
Price: 130.5
Quantity: 2
Total: 261.0

ItemName: Oil
Price: 80.5
Quantity: 1
Total: 80.5

total no. of items: 3

total bill: 463.5

In this program, we create two class variables itemCount and total_bill, and initialized them to zero. Three class instance variables are created, item, quantity, and, price. The value of them is initialized using the int () method. In the init method, we perform computations for total price and total_bill. The display them() function displays the details of all the items. Outside the class template, we create three objects II, 12, and 13 bypassing values of three items. Then display them() function is called three times for all three objects. Subsequently, the total item count and the total bill are displayed. Users can see the output for more lucidity.

While using the concepts of classes and objects one must consider the following points:

. The_init__( ) method is mandatory while using all the classes in python. It is a constructor method used for the instantiation of the object. This method is called implicity when an object of a class is created.

• All the methods and functions used inside classes of Python language contain an obligatory argument “self’. The argument self as it suggests refers to itself- the object which has called the method. That is if you have N objects calling the method, then self. a refers to a separate instance of the variable for each of the N objects.

• The variables declared inside the int__() method are data
members or instance variables of the class, whereas variables declared outside the init () method are called class variables.

• The class variables can be thought of as static variables as in C, C++, and Java. The class variables exhibit similar properties as that of a static variable. By virtue of this, they are used to count the number of instances created for a particular class. That means the value of class variables persists between different methods/function calls.

• The class variables are accessed outside the class definition by using the className then dot(.) operator and class variable name, e.g., className.class variable name.

• The data members and member functions of a class are accessed with the object name, dot operator, and variable name or method name, e.g., ObjectName.DataMemberName or ObjectName.MethodName

• The class template begins with the class keyword, then all the details of a class begin with an indentation. In the end, the unindented mark of the class represents the complete definition or exit from the class template.

• Unlike C++ or Java, Python does not require the main() function for declaring objects of classes. Only the unidentified mark represents that the user can create objects and use them.

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *