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.


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.


No comments: