Previous Index Next

Creating a Class

A class is a set of statements that define methods and data attributes. Let’s look at a simple example.

class Rectangle:
    def __init__(self, x, y):
        self.length = x
        self.width = y

    def get_area(self):
        return self.length * self.width

    def get_perimeter(self):
        return 2 * (self.length + self.width)

The above class have three methods

def __init__(self, x, y):
def get_area(self):
def get_perimeter(self):

Often, the first argument of a method is called self and required in every method of a class. Python replaces self with the object's name when the method is called from the object.

The __init__() method

In python, the built-in method __init__() is a special method that is used to initialize the data members of a class. It is the method that is automatically executed when an instance of the class is created in memory. The __init__() method is usually the first method inside a class definition.

Other class methods get_area() and get_perimeter() also have the required self parameter variable. When the method is called, self will automatically reference the object.

Creating Instance Objects

To create an instance object, call the class and pass the arguments, if required.

r = Rectangle(23,5)

Accessing Attributes

You access the object's attributes using the dot operator with object as follows −

a = r.get_area()
p = r.get_perimeter()

Now, putting all the concepts together:

Program (rectangle.py)

class Rectangle:
    def __init__(self, x, y):
        self.length = x
        self.width = y

    def get_area(self):
        return self.length * self.width

    def get_perimeter(self):
        return 2 * (self.length + self.width)


r = Rectangle(23,5)
a = r.get_area()
p = r.get_perimeter()

print('Area =',a)
print('Perimeter =',p)

Output

Area = 115
Perimeter = 56

Controlling Access to Members of a Class

To make a method or attribute private, start its name with two underscores. Private members are accessible only inside the class. The following example demonstrates this:

class Test:
    def __init__(self):
        self.a = 10
        self.__b = 5

    def display(self):
        print('a =', self.a)
        # private members are accessible within class 
        print('b =', self.__b)


t = Test()
print(t.a)
print(t.display())
# Error! not accesible outside class
print(t.b)
10
a = 10
b = 5
None
Traceback (most recent call last):
  File "C:/Users/91981/Desktop/Sample.py", line 17, in <module>
    print(t.b)
AttributeError: 'Test' object has no attribute 'b'

The __ str()__ method

It is a special function which returns the string representation of the objects. You can use a __str__ method when you want to display an object’s state. The following example demonstrates this:

class Demo:
    def __init__(self):
        self.message = 'hello world!'
        
    def __str__(self):
        return self.message

d = Demo()
print(d)

Output

hello world!

Previous Index Next