Classes and Objects

PYTHON OOPS CONCEPTS

  • Like other general-purpose programming languages, Python is also an object-oriented language since its beginning. It allows us to develop applications using an Object-Oriented approach. In Python, we can easily create and use classes and objects.
  • An object-oriented paradigm is to design the program using classes and objects. The object is related to real-world entities such as books, houses, pencils, etc. The oops concept focuses on writing the reusable code. It is a widespread technique to solve the problem by creating objects.
  • Major principles of object-oriented programming systems are given below.
    • Class
    • Object
    • Method
    • Inheritance
    • Polymorphism
    • Data Abstraction
    • Encapsulation

CLASS

  • The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. 
  • For example: if you have an employee class, then it should contain an attribute and method, i.e. an email id, name, age, salary, etc.
  • Syntax

OBJECT

  • The object is an entity that has a state and behavior. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc.
  • Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code.
  • When we define a class, it needs to create an object to allocate the memory. Consider the following example.
  • Example:

  • Output:

  • In the above example, we have created the class named car, and it has two attributes model name and year. We have created a c1 object to access the class attribute. The c1 object will allocate memory for these values.

METHOD

  • The method is a function that is associated with an object. In Python, a method is not unique to class instances. Any object type can have methods.

INHERITANCE

  • Inheritance is the most important aspect of object-oriented programming, which simulates the real-world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object.
  • By using inheritance, we can create a class that uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class.
  • It provides the reusability of the code.

POLYMORPHISM

  • Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means shape. By polymorphism, we understand that one task can be performed in different ways.
  • For example - you have a class animal, and all animals speak. But they speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on the animal. So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs and cats) have a concrete implementation of the action "speak".

ENCAPSULATION

  • Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.

DATA ABSTRACTION

  • Data abstraction and encapsulation are often used as synonyms. Both are nearly synonyms because data abstraction is achieved through encapsulation.
  • Abstraction is used to hide internal details and show only functionalities. Abstracting something means giving names to things so that the name captures the core of what a function or a whole program does.

OBJECT-ORIENTED VS. PROCEDURE-ORIENTED PROGRAMMING LANGUAGES

PYTHON CLASS AND OBJECTS

  • A class is a virtual entity and can be seen as a blueprint of an object. The class came into existence when it instantiated. Let's understand it by an example.
  • Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the building can be seen as a class, and we can create as many objects of this class.
  • On the other hand, the object is the instance of a class. The process of creating an object can be called instantiation.

CREATING CLASSES IN PYTHON

  • In Python, a class can be created by using the keyword class, followed by the class name. The syntax to create a class is given below.
  • Syntax
  • In Python, we must notice that each class is associated with a documentation string which can be accessed by using <class-name>.__doc__. A class contains a statement suite including fields, constructor, function, etc. definition.
  • Consider the following example to create a class Employee which contains two fields as Employee id, and name.
  • The class also contains a function display(), which is used to display the information of the Employee.
  • Example
  • Here, the self is used as a reference variable, which refers to the current class object. It is always the first argument in the function definition. However, using self is optional in the function call.
  • The self-parameter
    • The self-parameter refers to the current instance of the class and accesses the class variables. We can use anything instead of self, but it must be the first parameter of any function which belongs to the class.

CREATING AN INSTANCE OF THE CLASS

  • A class needs to be instantiated if we want to use the class attributes in another class or method. A class can be instantiated by calling the class using the class name.
  • The syntax to create the instance of the class is given below.
  • The following example creates the instance of the class Employee defined in the above example.
  • Example
  • Output
  • In the above code, we have created the Employee class which has two attributes named id and name, and assigned value to them. We can observe we have passed the self as a parameter in the display function. It is used to refer to the same class attribute.
  • We have created a new instance object named emp. By using it, we can access the attributes of the class.

DELETE THE OBJECT

  • We can delete the properties of the object or object itself by using the del keyword. Consider the following example.
  • Example
  • It will through the Attribute error because we have deleted the object emp.

PYTHON CONSTRUCTOR

  • A constructor is a special type of method (function) that is used to initialize the instance members of the class.
  • In C++ or Java, the constructor has the same name as its class, but it treats the constructor differently in Python. It is used to create an object.
  • Constructors can be of two types.
    1. Parameterized Constructor
    2. Non-parameterized Constructor
  • Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources for the object to perform any start-up task.

CREATING THE CONSTRUCTOR IN PYTHON

  • In Python, the method the __init__() simulates the constructor of the class. This method is called when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class.
  • We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.
  • Consider the following example to initialize the Employee class attributes.
  • Example
  • Output

COUNTING THE NUMBER OF OBJECTS OF A CLASS

  • The constructor is called automatically when we create the object of the class. Consider the following example.
  • Example
  • Output

PYTHON NON-PARAMETERIZED CONSTRUCTOR

  • The non-parameterized constructor uses when we do not want to manipulate the value or the constructor that has only self as an argument.
  • Consider the following example.

PYTHON PARAMETERIZED CONSTRUCTOR

  • The parameterized constructor has multiple parameters along with the self. Consider the following example.
  • Output

PYTHON DEFAULT CONSTRUCTOR

  • When we do not include the constructor in the class or forget to declare it, then that becomes the default constructor. It does not perform any task but initializes the objects. Consider the following example.
  • Output

MORE THAN ONE CONSTRUCTOR IN A SINGLE CLASS

  • Let's have a look at another scenario, what happens if we declare the two same constructors in the class.
  • Example
  • Output
  • In the above code, the object st called the second constructor whereas both have the same configuration. The first method is not accessible by the st object. Internally, the object of the class will always call the last constructor if the class has multiple constructors.
  • Note: The constructor overloading is not allowed in Python.

PYTHON BUILT-IN CLASS FUNCTIONS

  • The built-in functions defined in the class are described in the following table.
  • Example
  • Output

BUILT-IN CLASS ATTRIBUTES

  • The built-in class attributes are given in the below table.
  • Example
  • Output

Destroying Objects (Garbage Collection)

  • Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.
  • Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it change.
  • An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it is deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.
  • You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. However, a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non-memory resources used by an instance.
  • Example
  • This __del__() destructor prints the class name of an instance that is about to be destroyed −
  • When the above code is executed, it produces the following result −
  • Note − Ideally, you should define your classes in a separate file, then you should import them in your main program file using the import statement.
  • In the above example, assuming the definition of a Point class is contained in point.py and there is no other executable code in it.

Comments

Popular posts from this blog

Modules

Control Structures