Saturday, February 9, 2019

Classes in Python

Classes in Python have two types of attributes, data attributes and methods. Data attributes are like data members in C++. And methods are like member functions in C++. To use a class we need to create an instance of that class, called object. We don't use the class itself but use the object of any class. Classes only define the structure of how the object will be. We can create as many objects as we want, of a class. In the program below, rect is a class and r is an object of the rect class. Class rect has a method called setRect, and three data attributes width, height and area. The self parameter in setRect method is a reference to the class instance itself.

class rect:
def setRect(self, w, h):
self.width = w
self.height = h
self.area = w*h
r = rect()
r.setRect(9, 5)
print("Width =", r.width)
print("Height =", r.height)
print("Area =", r.area)
view raw Classes01.py hosted with ❤ by GitHub

The __init__() method:

The __init__() method in a class is called whenever an object of that class is created. The __init__() method is commonly used set the initial values of the data attributes of a class. It is like constructors in C++. In the following program we have used the __init__() method to set the width, height and area when the object r is created.

class rect:
def __init__(self, w, h):
self.width = w
self.height = h
self.area = w*h
def showRect(self):
print("Width =", r.width)
print("Height =", r.height)
print("Area =", r.area)
r = rect(9, 5)
r.showRect()
view raw Classes02.py hosted with ❤ by GitHub

No comments: