Author: Saim Khalid

  • MySQL Tutorial

    Introduction

    MySQL is (as of July 2013) the world’s most widely used open-source relational database management system (RDBMS), enabling the cost-effective delivery of reliable, high-performance and scalable Web-based and embedded database applications. It is widely-used as the database component of LAMP (Linux, Apache, MySQL, Perl/PHP/Python) web application software stack.

    MySQL was developed by Michael Widenius and David Axmark in 1994. Presently MySQL is maintained by Oracle (formerly Sun, formerly MySQL AB).

    MySQL tutorial of w3resource is a comprehensive tutorial to learn MySQL(5.6). We have hundreds of examples covered, often with PHP code. This helps you to learn how to create PHP-MySQL based web applications.

    Production Releases MySQL 5.6 : Latest General Availability (Production) release

    Table of Contents :

    • What is MySQL?
    • MySQL Editions
    • Who uses MySQL
    • Supported platforms Third party tools & Front ends tools
    • Key features, relational database features of MySQL
    • w3resource MySQL tutorials
    • Database Management System

    What is MySQL

    • MySQL is a database management system.
    • MySQL databases are relational.
    • MySQL software is Open Source.
    • The MySQL Database Server is fast, reliable, scalable, and easy to use.
    • MySQL Server works in client/server or embedded systems.
    • Initial release : 23 May 1995
    • Current stable release : 5.6.13 / 30 July 2013
    • Written in : C, C++
    • Operating system : Cross-platform
    • Available in : English
    • The license of MySQL is available under GNU General Public License (version 2) or proprietary EULA.
    • MySQL reduces the Total Cost of Ownership (TCO)
      • Reducing database licensing costs by over 90%
      • Cutting systems downtime by 60%
      • Lowering hardware expenditure by 70%
      • Reducing administration, engineering and support costs by up to 50%

    MySQL Editions

    There are five types MySQL editions.

    • MySQL Enterprise Edition : This edition includes the most comprehensive set of advanced features, management tools and technical support to achieve the highest levels of MySQL scalability, security, reliability, and uptime.
    • MySQL Standard Edition : This edition enables you to deliver high-performance and scalable Online Transaction Processing (OLTP) applications. It provides the ease of use that has made MySQL famous along with industrial-strength performance and reliability.
    • MySQL Classic Edition : This edition is the ideal embedded database for ISVs, OEMs, and VARs developing read-intensive applications using the MyISAM storage engine.
    • MySQL Cluster CGE : MySQL Cluster is a scalable, real-time, ACID-compliant database, combining 5 x 9s availability and open source technology. With a distributed, multi-master architecture and no single point of failure, MySQL Cluster scales horizontally on commodity hardware accessed via SQL and NoSQL APIs.
    • MySQL Embedded (OEM/ISV) : MySQL Database is a full-featured, zero-administration database that more than 3000 ISVs, OEMs, and VARs rely on to bring their products to market faster and make them more competitive.

    Who uses MySQL

    • Some of the most visited websites like Flickr, Facebook, Wikipedia, Google (not for search), YouTube.
    • Content Management Systems like WordPress, phpBB, Drupal, Joomla, TYPO3, MODx.
    • Last but not least, a large number of web developers across the world.

    MySQL supported platforms

    MySQL runs on

    • Linux (RedHat, SUSE, Mandrake, Debian)
    • Embedded Linux (MontaVista, LynuxWorks BlueCat)
    • Unix (Solaris, HP-UX, AIX)
    • BSD (Mac OS X, FreeBSD)
    • Windows (Windows 2000, Windows NT)
    • RTOS (QNX)

    MySQL supported third party tools

    Drivers :

    • ODBC
    • JDBC
    • .NET
    • C++

    Languages :

    • C
    • C++
    • C#
    • Java
    • Delphi
    • Visual Basic
    • Perl
    • Python
    • PHP

    Development Tools :

    • Microsoft Visual Studio
    • Borland Delphi and JBuilder
    • Eclipse
    • NetBeans

    Some of the widely used MySQL front ends (tools for managing MySQL)

    The MySQL GUI Tools Bundle is a cross-platform open source suite of desktop applications, building and manipulating the data within MySQL databases Development on the GUI Tools bundle has stopped, The GUI Tools bundle has been replaced by MySQL Workbench with the beta releases of MySQL Workbench 5.2. Currently, MySQL Workbench Team are working on Version 6.0. The first public beta, labeled version 6.0.2, was released on June 14, 2013.
    There are a lot of third-party free and proprietary graphical administration applications available that integrate with MySQL and users to work with the database. Here are some third-party tools for managing MySQL :

    ToolsDescription
    phpMyAdminThird party, Free, Web-based
    HeidiSQLThird party, Free, For Windows
    AdminerThird party, Free
    DBEditThird party, Free
    dbForge GUI ToolsThird party, Free
    NavicatThird party, Commercial
    MaatkitThird party, Command line, free
    MySQL SandboxThird party, Command line, free
    SQLBuddyA free Web-based front end, developed in PHP.
    SQLyogCommercial, but a free ‘community’ edition is available.
    Toad for MySQLThird party, free from Quest Software

    Key features of MySQL

    • MySQL follows ANSI SQL 99, the standard SQL.
    • Cross Platform.
    • Unicode support
    • ACID compliance
    • Stored procedures
    • Triggers
    • Cursors
    • Views
    • Information schema
    • Strict mode (ensures MySQL does not truncate or otherwise modify data to conform to an underlying data type when an incompatible value is inserted into that type)
    • Independent storage engines
    • Transactions with the InnoDB and NDB Cluster storage engines; savepoints with InnoDB
    • SSL support
    • Query caching
    • Sub-SELECTs (i.e. nested SELECTs)
    • Replication support (i.e. Master-Master Replication & Master-Slave Replication) with one master per slave, many slaves per master
    • Full-text indexing and searching using MyISAM engine
    • Embedded database library
    • Shared-nothing clustering through MySQL Cluster
    • Support for hotbackup
    • Multiple storage engines, allowing one to choose the one that is most effective for each table in the application
    • Commit grouping, gathering multiple transactions from multiple connections together to increase the number of commits per second.

    Key relational database features supported by MySQL

    • High-performance
    • Main-memory tables with disk-based tables
    • Single-User and Multi-User
    • Multi-Threaded
    • Multi-Process
    • SQL-92 and SQL-99
    • ACID Transactions
    • Referential Integrity
    • Cascading Updates and Deletes
    • Multi-table Joins
    • Row-level Locking
    • Online Hot Backup
    • Replication
    • Clustering
    • BLOBs (Binary Large Objects)
    • UDFs (User Defined Objects)
    • OLTP (On-Line Transaction Processing)
    • Unicode and Double-Byte character support
    • Drivers for ODBC, JDBC, .NET and C++

    Tutorial objectives

    1. A short and concise description to help you to understand about the topic / MySQL command.

    2. The syntax of the MySQL command with descriptions of all the parameters used.

    https://www.adsensecustomsearchads.com/afs/ads?psid=5134551505&channel=AutoRsVariant&cx=r-440389826592af9d2&fexp=21404%2C17301383%2C71847096&client=pub-2153208817642134&r=m&sct=ID%3Df1c5d672aa31266c%3AT%3D1706354011%3ART%3D1706354011%3AS%3DALNI_MZlJMMg_q5l3r_1tPiuFzhttpHLOQ&sc_status=6&hl=en&rpbu=http%3A%2F%2Fgoogle.com&rpqp=q&type=3&rs_tt=c&oe=UTF-8&ie=UTF-8&format=r5&nocache=781706400850607&num=0&output=afd_ads&domain_name=www.w3resource.com&v=3&bsl=10&pac=0&u_his=1&u_tz=-480&dt=1706400850609&u_w=1366&u_h=768&biw=1297&bih=644&psw=1297&psh=644&frm=0&cl=600476684&uio=-&cont=autors-container-0&drt=0&jsid=csa&jsv=600476684&rurl=https%3A%2F%2Fwww.w3resource.com%2Fmysql%2Fmysql-tutorials.php&referer=https%3A%2F%2Fwww.google.com%2F

    3. Display of the actual table on which the MySQL command is being applied.

    4. How that MySQL command can be executed with PHP.

    5. Explanation of the code.

    6. The output of the MySQL command when executed from windows command prompt.

    7. Display of the output with PHP in a separate browser window.

    8. After reading this largest third party online MySQL tutorial by w3resource, you will be able to install, manage and develop PHP-MySQL web applications by your own.

    9. You may refer MySQL Documentation along with this tutorial.

    We have a comprehensive, SQL TUTORIAL -2003 standard , which will help you to understand how to prepare queries to fetch data against various conditions.

  • Abstraction in Python

    Abstraction is used to hide the internal functionality of the function from the users. The users only interact with the basic implementation of the function, but inner working is hidden. User is familiar with that “what function does” but they don’t know “how it does.”

    In simple words, we all use the smartphone and very much familiar with its functions such as camera, voice-recorder, call-dialing, etc., but we don’t know how these operations are happening in the background. Let’s take another example – When we use the TV remote to increase the volume. We don’t know how pressing a key increases the volume of the TV. We only know to press the “+” button to increase the volume.

    That is exactly the abstraction that works in the object-oriented concept.

    Why Abstraction is Important?

    In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity. It also enhances the application efficiency. Next, we will learn how we can achieve abstraction using the Python program.

    Abstraction classes in Python

    In Python, abstraction can be achieved by using abstract classes and interfaces.

    A class that consists of one or more abstract method is called the abstract class. Abstract methods do not contain their implementation. Abstract class can be inherited by the subclass and abstract method gets its definition in the subclass. Abstraction classes are meant to be the blueprint of the other class. An abstract class can be useful when we are designing large functions. An abstract class is also helpful to provide the standard interface for different implementations of components. Python provides the abc module to use the abstraction in the Python program. Let’s see the following syntax.

    Syntax

    from abc import ABC  
    
    class ClassName(ABC):

    We import the ABC class from the abc module.

    Abstract Base Classes

    An abstract base class is the common application program of the interface for a set of subclasses. It can be used by the third-party, which will provide the implementations such as with plugins. It is also beneficial when we work with the large code-base hard to remember all the classes.

    Working of the Abstract Classes

    Unlike the other high-level language, Python doesn’t provide the abstract class itself. We need to import the abc module, which provides the base for defining Abstract Base classes (ABC). The ABC works by decorating methods of the base class as abstract. It registers concrete classes as the implementation of the abstract base. We use the @abstractmethod decorator to define an abstract method or if we don’t provide the definition to the method, it automatically becomes the abstract method. Let’s understand the following example.

    Example –

    # Python program demonstrate  
    
    # abstract base class work   
    
    from abc import ABC, abstractmethod   
    
    class Car(ABC):   
    
        def mileage(self):   
    
            pass  
    
      
    
    class Tesla(Car):   
    
        def mileage(self):   
    
            print("The mileage is 30kmph")   
    
    class Suzuki(Car):   
    
        def mileage(self):   
    
            print("The mileage is 25kmph ")   
    
    class Duster(Car):   
    
         def mileage(self):   
    
              print("The mileage is 24kmph ")   
    
      
    
    class Renault(Car):   
    
        def mileage(self):   
    
                print("The mileage is 27kmph ")   
    
              
    
    # Driver code   
    
    t= Tesla ()   
    
    t.mileage()   
    
      
    
    r = Renault()   
    
    r.mileage()   
    
      
    
    s = Suzuki()   
    
    s.mileage()   
    
    d = Duster()   
    
    d.mileage()

    Output:The mileage is 30kmph The mileage is 27kmph The mileage is 25kmph The mileage is 24kmph

    Explanation –

    In the above code, we have imported the abc module to create the abstract base class. We created the Car class that inherited the ABC class and defined an abstract method named mileage(). We have then inherited the base class from the three different subclasses and implemented the abstract method differently. We created the objects to call the abstract method.

    Let’s understand another example.

    Let’s understand another example.

    Example –

    # Python program to define   
    
    # abstract class  
    
      
    
    from abc import ABC  
    
      
    
    class Polygon(ABC):   
    
      
    
       # abstract method   
    
       def sides(self):   
    
          pass  
    
      
    
    class Triangle(Polygon):   
    
      
    
         
    
       def sides(self):   
    
          print("Triangle has 3 sides")   
    
      
    
    class Pentagon(Polygon):   
    
      
    
         
    
       def sides(self):   
    
          print("Pentagon has 5 sides")   
    
      
    
    class Hexagon(Polygon):   
    
      
    
       def sides(self):   
    
          print("Hexagon has 6 sides")   
    
      
    
    class square(Polygon):   
    
      
    
       def sides(self):   
    
          print("I have 4 sides")   
    
      
    
    # Driver code   
    
    t = Triangle()   
    
    t.sides()   
    
      
    
    s = square()   
    
    s.sides()   
    
      
    
    p = Pentagon()   
    
    p.sides()   
    
      
    
    k = Hexagon()   
    
    K.sides()

    Output:Triangle has 3 sides Square has 4 sides Pentagon has 5 sides Hexagon has 6 sides

    Explanation –

    In the above code, we have defined the abstract base class named Polygon and we also defined the abstract method. This base class inherited by the various subclasses. We implemented the abstract method in each subclass. We created the object of the subclasses and invoke the sides() method. The hidden implementations for the sides() method inside the each subclass comes into play. The abstract method sides() method, defined in the abstract class, is never invoked.

    Points to Remember

    Below are the points which we should remember about the abstract base class in Python.

    • An Abstract class can contain the both method normal and abstract method.
    • An Abstract cannot be instantiated; we cannot create objects for the abstract class.

    Abstraction is essential to hide the core functionality from the users. We have covered the all the basic concepts of Abstraction in Python.

  • Python Inheritance

    Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch.

    In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class. In this section of the tutorial, we will discuss inheritance in detail.

    In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name. Consider the following syntax to inherit a base class into the derived class.

    Python Inheritance

    Syntax

    class derived-class(base class):  
    
        <class-suite>

    A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax.

    Syntax

    class Animal:  
    
        def speak(self):  
    
            print("Animal Speaking")  
    
    #child class Dog inherits the base class Animal  
    
    class Dog(Animal):  
    
        def bark(self):  
    
            print("dog barking")  
    
    d = Dog()  
    
    d.bark()  
    
    d.speak()

    Example 1

    class Animal:  
    
        def speak(self):  
    
            print("Animal Speaking")  
    
    #child class Dog inherits the base class Animal  
    
    class Dog(Animal):  
    
        def bark(self):  
    
            print("dog barking")  
    
    d = Dog()  
    
    d.bark()  
    
    d.speak()

    Output:dog barking Animal Speaking


    Python Multi-Level inheritance

    Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is archived when a derived class inherits another derived class. There is no limit on the number of levels up to which, the multi-level inheritance is archived in python.

    Python Inheritance

    The syntax of multi-level inheritance is given below.

    Syntax

    class class1:  
    
        <class-suite>   
    
    class class2(class1):  
    
        <class suite>  
    
    class class3(class2):  
    
        <class suite>  
    
    .  
    
    .

    Example

    class Animal:  
    
        def speak(self):  
    
            print("Animal Speaking")  
    
    #The child class Dog inherits the base class Animal  
    
    class Dog(Animal):  
    
        def bark(self):  
    
            print("dog barking")  
    
    #The child class Dogchild inherits another child class Dog  
    
    class DogChild(Dog):  
    
        def eat(self):  
    
            print("Eating bread...")  
    
    d = DogChild()  
    
    d.bark()  
    
    d.speak()  
    
    d.eat()

    Output:dog barking Animal Speaking Eating bread…


    Python Multiple inheritance

    Python provides us the flexibility to inherit multiple base classes in the child class.

    Python Inheritance

    The syntax to perform multiple inheritance is given below.

    Syntax

    class Base1:  
    
        <class-suite>  
    
      
    
    class Base2:  
    
        <class-suite>  
    
    .  
    
    .  
    
    .  
    
    class BaseN:  
    
        <class-suite>  
    
      
    
    class Derived(Base1, Base2, ...... BaseN):  
    
        <class-suite>

    Example

    class Calculation1:  
    
        def Summation(self,a,b):  
    
            return a+b;  
    
    class Calculation2:  
    
        def Multiplication(self,a,b):  
    
            return a*b;  
    
    class Derived(Calculation1,Calculation2):  
    
        def Divide(self,a,b):  
    
            return a/b;  
    
    d = Derived()  
    
    print(d.Summation(10,20))  
    
    print(d.Multiplication(10,20))  
    
    print(d.Divide(10,20))

    Output:30 200 0.5


    The issubclass(sub,sup) method

    The issubclass(sub, sup) method is used to check the relationships between the specified classes. It returns true if the first class is the subclass of the second class, and false otherwise.

    Consider the following example.

    Example

    class Calculation1:  
    
        def Summation(self,a,b):  
    
            return a+b;  
    
    class Calculation2:  
    
        def Multiplication(self,a,b):  
    
            return a*b;  
    
    class Derived(Calculation1,Calculation2):  
    
        def Divide(self,a,b):  
    
            return a/b;  
    
    d = Derived()  
    
    print(issubclass(Derived,Calculation2))  
    
    print(issubclass(Calculation1,Calculation2))

    Output:True False


    The isinstance (obj, class) method

    The isinstance() method is used to check the relationship between the objects and classes. It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e., class.

    Consider the following example.

    Example

    class Calculation1:  
    
        def Summation(self,a,b):  
    
            return a+b;  
    
    class Calculation2:  
    
        def Multiplication(self,a,b):  
    
            return a*b;  
    
    class Derived(Calculation1,Calculation2):  
    
        def Divide(self,a,b):  
    
            return a/b;  
    
    d = Derived()  
    
    print(isinstance(d,Derived))

    Output:


    Method Overriding

    We can provide some specific implementation of the parent class method in our child class. When the parent class method is defined in the child class with some specific implementation, then the concept is called method overriding. We may need to perform method overriding in the scenario where the different definition of a parent class method is needed in the child class.

    Consider the following example to perform method overriding in python.

    Example

    class Animal:  
    
        def speak(self):  
    
            print("speaking")  
    
    class Dog(Animal):  
    
        def speak(self):  
    
            print("Barking")  
    
    d = Dog()  
    
    d.speak()

    Output:Barking

    Real Life Example of method overriding

    
    
    1. class Bank:  
    2.     def getroi(self):  
    3.         return 10;  
    4. class SBI(Bank):  
    5.     def getroi(self):  
    6.         return 7;  
    7.   
    8. class ICICI(Bank):  
    9.     def getroi(self):  
    10.         return 8;  
    11. b1 = Bank()  
    12. b2 = SBI()  
    13. b3 = ICICI()  
    14. print("Bank Rate of interest:",b1.getroi());  
    15. print("SBI Rate of interest:",b2.getroi());  
    16. print("ICICI Rate of interest:",b3.getroi());

    Output:Bank Rate of interest: 10 SBI Rate of interest: 7 ICICI Rate of interest: 8


    Data abstraction in python

    Abstraction is an important aspect of object-oriented programming. In python, we can also perform data hiding by adding the double underscore (___) as a prefix to the attribute which is to be hidden. After this, the attribute will not be visible outside of the class through the object.

    Consider the following example.

    Example

    
    
    1. class Employee:  
    2.     __count = 0;  
    3.     def __init__(self):  
    4.         Employee.__count = Employee.__count+1  
    5.     def display(self):  
    6.         print("The number of employees",Employee.__count)  
    7. emp = Employee()  
    8. emp2 = Employee()  
    9. try:  
    10.     print(emp.__count)  
    11. finally:  
    12.     emp.display()

    Output:The number of employees 2 AttributeError: ‘Employee’ object has no attribute ‘__count’

  • Python Constructor

    A constructor is a special type of method (function) which 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 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

    class Employee:  
    
        def __init__(self, name, id):  
    
            self.id = id  
    
            self.name = name  
    
      
    
        def display(self):  
    
            print("ID: %d \nName: %s" % (self.id, self.name))  
    
      
    
      
    
    emp1 = Employee("John", 101)  
    
    emp2 = Employee("David", 102)  
    
      
    
    # accessing display() method to print employee 1 information  
    
      
    
    emp1.display()  
    
      
    
    # accessing display() method to print employee 2 information  
    
    emp2.display()

    Output:ID: 101 Name: John ID: 102 Name: David

    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

    class Student:    
    
        count = 0    
    
        def __init__(self):    
    
            Student.count = Student.count + 1    
    
    s1=Student()    
    
    s2=Student()    
    
    s3=Student()    
    
    print("The number of students:",Student.count)

    Output:The number of students: 3

    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.

    Example

    class Student:  
    
        # Constructor - non parameterized  
    
        def __init__(self):  
    
            print("This is non parametrized constructor")  
    
        def show(self,name):  
    
            print("Hello",name)  
    
    student = Student()  
    
    student.show("John")

    Python Parameterized Constructor

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

    Example

    class Student:  
    
        # Constructor - parameterized  
    
        def __init__(self, name):  
    
            print("This is parametrized constructor")  
    
            self.name = name  
    
        def show(self):  
    
            print("Hello",self.name)  
    
    student = Student("John")  
    
    student.show()

    Output:This is parametrized constructor Hello John

    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.

    Example

    class Student:  
    
        roll_num = 101  
    
        name = "Joseph"  
    
      
    
        def display(self):  
    
            print(self.roll_num,self.name)  
    
      
    
    st = Student()  
    
    st.display()

    Output:101 Joseph

    More than One Constructor in Single class

    Let’s have a look at another scenario, what happen if we declare the two same constructors in the class.

    Example

    class Student:  
    
        def __init__(self):  
    
            print("The First Constructor")  
    
        def __init__(self):  
    
            print("The second contructor")  
    
      
    
    st = Student()

    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.

    SNFunctionDescription
    1getattr(obj,name,default)It is used to access the attribute of the object.
    2setattr(obj, name,value)It is used to set a particular value to the specific attribute of an object.
    3delattr(obj, name)It is used to delete a specific attribute.
    4hasattr(obj, name)It returns true if the object contains some specific attribute.

    Example

      class Student:  
      
          def __init__(self, name, id, age):  
      
              self.name = name  
      
              self.id = id  
      
              self.age = age  
      
        
      
          # creates the object of the class Student  
      
      s = Student("John", 101, 22)  
      
        
      
      # prints the attribute name of the object s  
      
      print(getattr(s, 'name'))  
      
        
      
      # reset the value of attribute age to 23  
      
      setattr(s, "age", 23)  
      
        
      
      # prints the modified value of age  
      
      print(getattr(s, 'age'))  
      
        
      
      # prints true if the student contains the attribute with name id  
      
        
      
      print(hasattr(s, 'id'))  
      
      # deletes the attribute age  
      
      delattr(s, 'age')  
      
        
      
      # this will give an error since the attribute age has been deleted  
      
      print(s.age)

      Output:John 23 True AttributeError: ‘Student’ object has no attribute ‘age’

      Built-in class attributes

      Along with the other attributes, a Python class also contains some built-in class attributes which provide information about the class.

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

      SNAttributeDescription
      1__dict__It provides the dictionary containing the information about the class namespace.
      2__doc__It contains a string which has the class documentation
      3__name__It is used to access the class name.
      4__module__It is used to access the module in which, this class is defined.
      5__bases__It contains a tuple including all base classes.

      Example

      class Student:    
      
          def __init__(self,name,id,age):    
      
              self.name = name;    
      
              self.id = id;    
      
              self.age = age    
      
          def display_details(self):    
      
              print("Name:%s, ID:%d, age:%d"%(self.name,self.id))    
      
      s = Student("John",101,22)    
      
      print(s.__doc__)    
      
      print(s.__dict__)    
      
      print(s.__module__)

      Output:None {‘name’: ‘John’, ‘id’: 101, ‘age’: 22} __main__

    1. Classes and Objects in Python

      Python is an object-oriented programming language that offers classes, which are a potent tool for writing reusable code. To describe objects with shared characteristics and behaviours, classes are utilised. We shall examine Python’s ideas of classes and objects in this article.

      Classes in Python:

      In Python, a class is a user-defined data type that contains both the data itself and the methods that may be used to manipulate it. In a sense, classes serve as a template to create objects. They provide the characteristics and operations that the objects will employ.

      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.

      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

      class ClassName:    
      
          #statement_suite

      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.

      Example:

      Code:

      class Person:  
      
          def __init__(self, name, age):  
      
              # This is the constructor method that is called when creating a new Person object  
      
              # It takes two parameters, name and age, and initializes them as attributes of the object  
      
              self.name = name  
      
              self.age = age  
      
          def greet(self):  
      
              # This is a method of the Person class that prints a greeting message  
      
              print("Hello, my name is " + self.name)

      Name and age are the two properties of the Person class. Additionally, it has a function called greet that prints a greeting.

      Objects in Python:

      An object is a particular instance of a class with unique characteristics and functions. After a class has been established, you may make objects based on it. By using the class constructor, you may create an object of a class in Python. The object’s attributes are initialised in the constructor, which is a special procedure with the name __init__.

      Syntax:

      
      
      1. # Declare an object of a class  
      2. object_name = Class_Name(arguments) 

      Example:

      Code:

      class Person:  
      
          def __init__(self, name, age):  
      
              self.name = name    
      
              self.age = age      
      
          def greet(self):  
      
              print("Hello, my name is " + self.name)  
      
        
      
      # Create a new instance of the Person class and assign it to the variable person1  
      
      person1 = Person("Ayan", 25)  
      
      person1.greet()

      Output:“Hello, my name is Ayan”

      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.

      _ _init_ _ method

      In order to make an instance of a class in Python, a specific function called __init__ is called. Although it is used to set the object’s attributes, it is often referred to as a constructor.

      The self-argument is the only one required by the __init__ method. This argument refers to the newly generated instance of the class. To initialise the values of each attribute associated with the objects, you can declare extra arguments in the __init__ method.

      Class and Instance Variables

      All instances of a class exchange class variables. They function independently of any class methods and may be accessed through the use of the class name. Here’s an illustration:

      Code:

      class Person:  
      
          count = 0   # This is a class variable  
      
        
      
          def __init__(self, name, age):  
      
              self.name = name    # This is an instance variable  
      
              self.age = age  
      
              Person.count += 1   # Accessing the class variable using the name of the class  
      
      person1 = Person("Ayan", 25)  
      
      person2 = Person("Bobby", 30)  
      
      print(Person.count)

      Output:2

      Whereas, instance variables are specific to each instance of a class. They are specified using the self-argument in the __init__ method. Here’s an illustration:

      Code:

      class Person:  
      
          def __init__(self, name, age):  
      
              self.name = name    # This is an instance variable  
      
              self.age = age  
      
      person1 = Person("Ayan", 25)  
      
      person2 = Person("Bobby", 30)  
      
      print(person1.name)    
      
      print(person2.age)

      Output:Ayan 30

      Class variables are created separately from any class methods and are shared by all class copies. Every instance of a class has its own instance variables, which are specified in the __init__ method utilising the self-argument.

      Conclusion:

      In conclusion, Python’s classes and objects notions are strong ideas that let you write reusable programmes. You may combine information and capabilities into a single entity that is able to be used to build many objects by establishing a class. Using the dot notation, you may access an object’s methods and properties after it has been created. You can develop more logical, effective, and manageable code by comprehending Python’s classes and objects.

    2. 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-word entities such as book, house, pencil, 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 system 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

      class ClassName:     
      
              <statement-1>     
      
              .     
      
              .      
      
              <statement-N>

      Object

      The object is an entity that has state and behavior. It may be any real-world object like the 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:

      class car:  
      
          def __init__(self,modelname, year):  
      
              self.modelname = modelname  
      
              self.year = year  
      
          def display(self):  
      
              print(self.modelname,self.year)  
      
        
      
      c1 = car("Toyota", 2016)  
      
      c1.display()

      Output:Toyota 2016

      In the above example, we have created the class named car, and it has two attributes modelname and year. We have created a c1 object to access the class attribute. The c1 object will allocate memory for these values. We will learn more about class and object in the next tutorial.

      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 which 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 re-usability 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 both 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 to give 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

      The difference between object-oriented and procedure-oriented programming is given below:

      IndexObject-oriented ProgrammingProcedural Programming
      1.Object-oriented programming is the problem-solving approach and used where computation is done by using objects.Procedural programming uses a list of instructions to do computation step by step.
      2.It makes the development and maintenance easier.In procedural programming, It is not easy to maintain the codes when the project becomes lengthy.
      3.It simulates the real world entity. So real-world problems can be easily solved through oops.It doesn’t simulate the real world. It works on step by step instructions divided into small parts called functions.
      4.It provides data hiding. So it is more secure than procedural languages. You cannot access private data from anywhere.Procedural language doesn’t provide any proper way for data binding, so it is less secure.
      5.Example of object-oriented programming languages is C++, Java, .Net, Python, C#, etc.Example of procedural languages are: C, Fortran, Pascal, VB etc.
    3. Second Largest Number in Python

      When we have a lot of elements in our list, the thought of finding the highest or lowest element can come to our mind and Python has made it much easier for us.

      In this article, we shall how we can use to find the second largest number in Python from a list.

      1. Sorting the list and then print the second last number.
      2. Removing the maximum element.
      3. Finding the maximum element.
      4. Traversing the list.

      Let us have a look at the first approach-

      Sorting the list and then print the second last number

      The following program illustrates how we can do it in Python-

      Example –

      #program to find the second largest number of list  
      
      # declaring the list  
      
      list_val = [20, 30, 40, 25, 10]  
      
      # sorting the list  
      
      list_val.sort()  
      
      #displaying the second last element of the list  
      
      print("The second largest element of the list is:", list_val[-2])

      Output:The second largest element of the list is: 30

      It’s time to go for the explanation part-

      1. We have declared the list from which we want to take out the second last element.
      2. After this, we used the sort method so that all the elements of our list are arranged in ascending order.
      3. Now we make use of negative indexing since the second-largest number will come at the second last position.

      The second method is to obtain the second largest element of the list by removing the maximum element.

      Let us see how we can do it.

      Removing the maximum element

      Example –

      #program to find the second largest number of list  
      
        
      
      # declaring the list  
      
      list_val = [20, 30, 40, 25, 10]  
      
        
      
      # new_list is a set of list1  
      
      res_list = set(list_val)  
      
        
      
      #removing the maximum element  
      
      res_list.remove(max(res_list))  
      
        
      
      #printing the second largest element   
      
      print(max(res_list))

      Output:30

      Explanation –

      Let us understand what we have done in the above program-

      1. We have declared the list from which we want to take out the second last element.
      2. After this, we used the set method to take all the unique elements of the list.
      3. Now we make use of max() to get the maximum value from the list and then remove it.
      4. After this, we print the maximum of the resultant list which will give us the second-largest number.

      In the third method, we will use for loop and find the second largest number from the list.

      Example –

      # declaring empty list  
      
      list_val = []  
      
        
      
      # user provides the number of elements to be added in the list  
      
      num_list = int(input("Enter number of elements in list: "))  
      
        
      
        
      
      for i in range(1, num_list + 1):  
      
          element = int(input("Enter the elements: "))  
      
          list_val.append(element)  
      
        
      
        
      
      # sort the list  
      
      list_val.sort()  
      
            
      
      # print second largest element  
      
      print("Second largest element is:", list_val[-2])

      Output:Enter number of elements in list: 5 Enter the elements: 10 Enter the elements: 20 Enter the elements: 30 Enter the elements: 40 Enter the elements: 50 The second largest element is: 40

      Explanation –

      Let us have a glance at what we have done here-

      1. We have declared an empty list in which we will insert the elements.
      2. After this, we ask the user to provide us the number of elements we would like to add to our list.
      3. After this, we use the sort method so that all the elements of our list are arranged in ascending order.
      4. Now we make use of negative indexing since the second-largest number will come at the second last position.

      Traversing the list

      In the last program, we will traverse the list to find out the largest number and then make use of conditional statements to find the second largest number from the list.

      The following program illustrates the same-

      Example –

      
      
      1. def calc_largest(arr):  
      2.     second_largest = arr[0]  
      3.     largest_val = arr[0]  
      4.     for i in range(len(arr)):  
      5.         if arr[i] > largest_val:  
      6.             largest_val = arr[i]  
      7.   
      8.     for i in range(len(arr)):  
      9.         if arr[i] > second_largest and arr[i] != largest_val:  
      10.             second_largest = arr[i]  
      11.   
      12.     return second_largest  
      13. print(calc_largest([20, 30, 40, 25, 10])) 

      Output:

      Explanation –

      Let us understand what we have done in the above program-

      1. The first step is to create a function that checks the largest number from the list by traversing it.
      2. In the next for loop, we traverse the list again for finding the highest number but this time excludes the previous one since here our objective is to find the second largest function.
      3. Finally, we pass our list in the function.

      So, in this article, we got the chance to think out of the box and discover some new ways to develop the logic for finding the second largest number in Python.

    4. Python SimpleImputer module

      In this tutorial, we are going to learn about the SimpleImputer module of the Sklearn library, and it was previously known as impute module but updated in the latest versions of the Sklearn library. We will discuss the SimpleImputer class and how we can use it to handle missing data in a dataset and replace the missing values inside the dataset using a Python program.

      SimpleImputer class

      A scikit-learn class that we can use to handle the missing values in the data from the dataset of a predictive model is called SimpleImputer class. With the help of this class, we can replace NaN (missing values) values in the dataset with a specified placeholder. We can implement and use this module class by using the SimpleImputer() method in the program.

      Syntax for SimpleImputer() method:

      To implement the SimpleImputer() class method into a Python program, we have to use the following syntax:

      1. SimpleImputer(missingValues, strategy)  

      Parameters: Following are the parameters which has to be defined while using the SimpleImputer() method:

      1. missingValues: It is the missing values placeholder in the SimpleImputer() method which has to be imputed during the execution, and by default, the value for missing values placeholder is NaN.
      2. strategy: It is the data that is going to replace the missing values (NaN values) from the dataset, and by default, the value method for this parameter is ‘Mean’. The strategy parameter of the SimpleImputer() method can take ‘Mean’, ‘Mode’, Median’ (Central tendency measuring methods) and ‘Constant’ value input in it.
      3. fillValue: This parameter is used only in the strategy parameter if we give ‘Constant’ as replacing value method. We have to define the constant value for the strategy parameter, which is going to replace the NaN values from the dataset.

      SimpleImputer class is the module class of Sklearn library, and to use this class, first we have to install the Sklearn library in our system if it is not present already.

      Installation of Sklearn library:

      We can install the Sklearn by using the following command inside the command terminal prompt of our system:

      pip install sklearn  

      After pressing the enter key, the sklearn module will start installing in our device, as we can see below:

      Python SimpleImputer module

      Now, the Sklearn module is installed in our system, and we can move ahead with the SimpleImputer class function.

      Handling NaN values in the dataset with SimpleImputer class

      Now, we will use the SimpleImputer class in a Python program to handle the missing values present in the dataset (that we will use in the program). We will define a dataset in the example program while giving some missing values in it, and then we use the SimpleImputer class method to handle those values from the dataset by defining its parameters. Let’s understand the implementation of this through an example Python program.

      Example 1: Look at the following Python program with a dataset having NaN values defined in it:

      # Import numpy module as nmp  
      
      import numpy as nmp  
      
      # Importing SimpleImputer class from sklearn impute module  
      
      from sklearn.impute import SimpleImputer  
      
      # Setting up imputer function variable  
      
      imputerFunc = SimpleImputer(missing_values = nmp.nan, strategy ='mean')  
      
      # Defining a dataset  
      
      dataSet = [[32, nmp.nan, 34, 47], [17, nmp.nan, 71, 53], [19, 29, nmp.nan, 79], [nmp.nan, 31, 23, 37], [19, nmp.nan, 79, 53]]  
      
      # Print original dataset  
      
      print("The Original Dataset we defined in the program: \n", dataSet)  
      
      # Imputing dataset by replacing missing values  
      
      imputerFunc = imputerFunc.fit(dataSet)  
      
      dataSet2 = imputerFunc.transform(dataSet)  
      
      # Printing imputed dataset  
      
      print("The imputed dataset after replacing missing values from it: \n", dataSet2)

      Output:The Original Dataset we defined in the program: [[32, nan, 34, 47], [17, nan, 71, 53], [19, 29, nan, 79], [nan, 31, 23, 37], [19, nan, 79, 53]] The imputed dataset after replacing missing values from it: [[32. 30. 34. 47. ] [17. 30. 71. 53. ] [19. 29. 51.75 79. ] [21.75 31. 23. 37. ] [19. 30. 79. 53. ]]

      Explanation:

      We have firstly imported the numpy module (to define a dataset) and sklearn module (to use the SimpleImputer class method) into the program. Then, we defined the imputer to handle the missing values using the SimpleImputer class method, and we used the ‘mean’ strategy to replace the missing values from the dataset. After that, we have defined a dataset in the program using the numpy module function and gave some missing values (NaN values) in the dataset. Then, we printed the original dataset in the output. After that, we have imputed and replaced the missing values from the dataset with the imputer that we have defined earlier in the program with SimpleImputer class. After imputing the dataset and replacing the missing values from it, we have printed the new dataset as a result.

      As we can see in the output, the imputed value dataset having mean values in the place of missing values, and that’s how we can use the SimpleImputer module class to handle NaN values from a dataset.

      Conclusion

      We have read about the SimpleImputer class method in this method, and we learned how we could use it to handle the NaN values present in a dataset. We learned about the strategy value parameter, which we use to define the method for replacing the NaN values of the dataset. We have also learned about the installation of the Sklearn library, and then last, we used the SimpleImputer class method in an example to impute the dataset.

    5. Python OpenCV object detection

      OpenCV is the huge and open-source library for image processing, machine learning and computer vision. It is also playing an important role in real-time operation. With the help of the OpenCV library, we can easily process the images as well as videos to identify the objects, faces or even handwriting of a human present in the file. We will only focus to object detection from images using OpenCV in this tutorial. We will learn about how we can use OpenCV to do object detection from a given image using a Python program.

      Object Detection

      Basically, object detection is a modern computer technology that is related to image processing, deep learning and computer vision to detect the objects present in an image file. All the technologies used in the Object detection technique (as we mentioned earlier) deals with detecting instances of the object in the image or video.

      Object Detection using OpenCV

      We have learned about object detection in the previous section, and in this section, we will learn that how we can do object detection in an image or video using the OpenCV library. We will first import the OpenCV library in the Python program, and then we will use functions to perform object detection on an image file given to us. But, before using and importing the library functions, let’s first install the requirements for using the Object detection technique.

      In this tutorial, we will use the Haar cascade technique to do object detection. Let’s learn in brief about the Haar cascade technique first.

      Haar cascade:

      Basically, the Haar cascade technique is an approach based on machine learning where we use a lot of positive and negative images to train the classifier to classify between the images. Haar cascade classifiers are considered as the effective way to do object detection with the OpenCV library. Now, let’s understand the concept of positive and negative images that we have discussed earlier:

      • Positive images: These are the images that contain the objects which we want to be identified from the classifier.
      • Negative Images: These are the images that do not contain any object that we want to be detected by the classifier, and these can be images of everything else.

      Requirements for object detection with Python OpenCV:

      We have to install first some important libraries in our system as it is an important requirement for doing object detection tasks. We have to install the following libraries into our system as the requirement for performing object detection:

      1. Installation of OpenCV library:

      First and foremost, the requirement to perform object detection using the OpenCV library is that the OpenCV library should be present in our device so that we can import it into a Python program and use its object detection functions. If this library is not present in our system, we can use the following command in our command prompt terminal to install it:

      pip install opencv-python  
      Python OpenCV object detection

      When we press the enter key after writing this command in the terminal, the pip installer in the command prompt will start installing the OpenCV library into our system.

      Python OpenCV object detection

      As we can see that, the OpenCV library is successfully installed in our system, and now we can import it into a Python program to use its functions.

      2. Installation of matplotlib library:

      Matplotlib is very helpful in the opening, closing, reading etc., images in a Python program, and that’s why the installation of this library for object detection becomes an important requirement. If the matplotlib library is not present in our system, we have to use the following command in our command prompt terminal to install it:

      pip install matplotlib  
      Python OpenCV object detection

      When we press the enter key after writing this command in the terminal, the pip installer in the command prompt will start installing it into our system.

      Python OpenCV object detection

      As we can see that, the matplotlib library is successfully installed in our system, and now we can import it into a Python program to use its functions for opening, reading etc., images.

      We have installed all the required libraries for performing object detection, and now we can move ahead with the implementation part of this task.

      Implementation of Object detection in Python:

      In this part, we will write the Python programs to do the object detection and understand the implementation of it. We will use the following image in our Python program to perform the object detection on it:

      Python OpenCV object detection

      Opening the Image

      We will first open the image given above and create the environment of the picture to show it in the output. Let’s first look at an example program to understand the implementation, and then we will look at the explanation part.

      Example 1: Opening the image using OpenCV and matplotlib library in a Python program:

      # Import OpenCV module  
      
      import cv2  
      
      # Import pyplot from matplotlib as pltd  
      
      from matplotlib import pyplot as pltd  
      
      # Opening the image from files  
      
      imaging = cv2.imread("opencv-od.png")  
      
      # Altering properties of image with cv2  
      
      img_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY)  
      
      imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB)  
      
      # Plotting image with subplot() from plt  
      
      pltd.subplot(1, 1, 1)  
      
      # Displaying image in the output  
      
      pltd.imshow(imaging_rgb)  
      
      pltd.show()

      Output:

      Python OpenCV object detection

      Explanation:

      First, we have imported the OpenCV (as cv2) and matplotlib (as plt) libraries into the program to use their functions in the code. After that, we have opened the image file using the imread() function of cv2.

      Then, we have defined the properties for the image we opened in the program using the cv2 functions. Then, we subplot the image using the subplot() function of plt and giving parameters in it. In last, we have used the imshow() and show() function of the plt module to show the image in the output.

      As we can see in the output, the image is displayed as a result of the program, and its borders have been sub-plotted.

      Recognition or object detection in the image

      Now, we will use the detectMultiScale() in the program to detect the object present in the image. Following is the syntax for using detectMultiScale() function in the code:

      found = xml_data.detectMultiScale(img_gray,   
      
                                         minSize = (30, 30))

      We will use a condition statement with this function in the program to check if any object from the image is detected or not and highlight the detected part. Let’s understand the implementation of object detection in the image through an example program.

      Example 2: Object detection in the image using the detectMultiScale() in the following Python program:

      # Import OpenCV module  
      
      import cv2  
      
      # Import pyplot from matplotlib as plt  
      
      from matplotlib import pyplot as pltd  
      
      # Opening the image from files  
      
      imaging = cv2.imread("opencv-od.png")  
      
      # Altering properties of image with cv2  
      
      imaging_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY)  
      
      imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB)  
      
      # Importing Haar cascade classifier xml data  
      
      xml_data = cv2.CascadeClassifier('XML-data.xml')  
      
      # Detecting object in the image with Haar cascade classifier   
      
      detecting = xml_data.detectMultiScale(imaging_gray,   
      
                                         minSize = (30, 30))  
      
      # Amount of object detected  
      
      amountDetecting = len(detecting)  
      
      # Using if condition to highlight the object detected  
      
      if amountDetecting != 0:  
      
          for (a, b, width, height) in detecting:  
      
              cv2.rectangle(imaging_rgb, (a, b), # Highlighting detected object with rectangle  
      
                            (a + height, b + width),   
      
                            (0, 275, 0), 9)  
      
      # Plotting image with subplot() from plt  
      
      pltd.subplot(1, 1, 1)  
      
      # Displaying image in the output  
      
      pltd.imshow(imaging_rgb)  
      
      pltd.show()

      Output:

      Python OpenCV object detection

      Explanation:

      After opening the image in the program, we have imported the cascade classifier XML file into the program. Then, we used the detectMultiScale() function with the imported cascade file to detect the object present in the image or not.

      We used if condition in the program to check that object is detected or not, and if the object is detected, we have highlighted the detected object part using for loop with cv2 functions. After highlighting the detected object part in the image, we have displayed the processed image using the plt show() and imshow() function.

      As we can see in the output, the image with the object detected part as highlighted is shown to us when we run the program.

    6. nsetools in Python

      In the following tutorial, we will discuss the nsetools library in the Python programming language. We will understand its features and work with some examples.

      So, let’s get started.

      Understanding the nsetools library

      NSE or National Stock Exchange of India Limited is the leading stock exchange of India, situated in Mumbai, Maharashtra. NSE was established in the year 1992 as the first dematerialized electronic exchange in the country.

      Python offers a library that allows the programmers to collect real-time data from National Stock Exchange (India). This library is known as nsetools. We can use this library in different projects, which requires fetching live quotes for a provided index or stock or creating large sets of data for further data analytics. We can also create Command-Line Interface (CLI) Applications that may deliver us the details of the live market at a blazing fast speed, pretty faster than any web browser. The data accuracy is only as correct as provided on the official website of the National Stock Exchange of India Limited. (http://www.nseindia.com)

      Main features of the Python nsetools library

      Some of the key features of the Python nsetools library are stated as follows:

      The nsetools library works out of the box, without any setup requirement.
      
      This library helps programmers to fetch livestock code and index codes at blazing fast speed.
      
      It also offers a set of all stocks and indices traded on the National Stock Exchange.
      
      Moreover, it also provides a set of:
      
      Top losers
      
      Top gainers
      
      Most active
      
      It also delivers several helpful Application Programming Interfaces (APIs) in order to validate a stock code and index code.
      
      The library optionally returns data in JSON format.
      
      It has a hundred per cent Unit test coverage.

      How to install the Python nsetools library?

      The installation part of the nsetools library is quite easy, and it has no external dependencies. All the dependencies of the library are part of standard distribution packages of Python. We can install the nsetools library using the pip installer as shown in the following syntax:

      Syntax:

      $ pip install nsetools  

      Updating the library

      If some of us already have installed the nsetools library in their systems, then the following command will allow them to update the library.

      Syntax:

      $ pip install nsetools -upgrade  

      Python 3 support

      Python 3 support for the library has been included from version 1.0.0 and so on. Now, this library is able to work for both Python 2 as well as Python 3.

      Creating an NSE object

      We can create an NSE object using the Nse() function offered by the nsetools library. The same can be seen in the following example:

      Example:

      
      
      1. # importing the Nse() function from the nsetools library  
      2. from nsetools import Nse  
      3.   
      4. # creating an NSE object  
      5. nse_obj = Nse()  
      6.   
      7. # printing the value of the object  
      8. print("NSE Object:", nse_obj) 

      Output:NSE Object: Driver Class for National Stock Exchange (NSE)

      Explanation:

      In the above snippet of code, we have imported the required function from the library. We have then defined a variable that uses the Nse() function to create an NSE object. We have then printed the value of the variable for the users.

      Getting Information using the nsetools library

      Let us consider an example demonstrating the use of nsetools for gathering Information.

      Example:

      
      
      1. # importing the Nse() function from the nsetools library  
      2. from nsetools import Nse  
      3.   
      4. # creating an NSE object  
      5. nse_obj = Nse()  
      6.   
      7. # getting quotation of the company  
      8. the_quotation = nse_obj.get_quote('sbin')  
      9.   
      10. # printing the name of the company  
      11. print(the_quotation["companyName"])  
      12.   
      13. # printing average price  
      14. print("Average Price: " + str(the_quotation["averagePrice"])) 

      Output:State Bank of India Average Price: 431.97

      Explanation:

      In the above snippet of code, we have imported the required module and created an NSE object using the Nse() function. We have then defined another variable that uses the get_quote() function on the NSE object to get the quotation of the specified company. We have then printed the required details for the users.