A: Encapsulation and inheritance part - 1
This is an introductory paragraph on encapsulation.
Encapsulation is the mechanism that we use to store data in a secure manner, and access it using procedures and functions.
The following example will illustrate the working of encapsulation:
#encoding: utf-8 class Car: def __init__(self, color, model): self.color = color self.model = model def get_colour(self): return self.color def set_colour(self, color): self.color = color def __str__(self): return "Car: Model %s, Color %s" % (self.model, self.color) car = Car("Red", "Sport") print(car.get_colour()) car.set_colour("Blue") print(car.get_colour())
Blue Car: Model Sport, Color Blue
A: Encapsulation and inheritance part - 2
Encapsulation is the concept of bundling the data with the procedure's working in order to protect it from unauthorized access. It can also be called data hiding. This means that no one other than the procedure creator can access the data. This concept is useful in developing programs that are secure or are used by other people in your organization or in your family. If you have a program at your work place which looks at all the employee's salaries and calculates bonuses, you do not want any other person to look at this information or to change it, so you would use encapsulation in this case. Encapsulation makes sure that no one can access the data unless he knows the procedure that was created to read it.
Inheritance is the process of creating new classes based on existing classes. Inheritance allows you to create classes that are similar, but not identical to each other. The new class inherits all the attributes of its parent class, but it can also have its own attributes and methods to make it more specialized for its intended purpose. For example, you can inherit a class called Bird from a class called Animal . You can then make several different classes like Parrot , Ostrich , and Penguin out of Bird . They share some common traits with Bird , but each has its own unique attributes as well.