Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-MCA-Python Programming- Second Draft

CU-MCA-Python Programming- Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-10-12 04:11:27

Description: CU-MCA-Python Programming- Second Draft

Search

Read the Text Version

# list of letters letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] # function that filters vowels def filter_vowels(letter): vowels = ['a', 'e', 'i', 'o', 'u'] if(letter in vowels): return True else: return False filtered_vowels = filter(filter_vowels, letters) print('The filtered vowels are:') for vowel in filtered_vowels: print(vowel) Output The filtered vowels are: a e i o 4.10REDUCE () FUNCTION It is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in “functools” module. Syntax reduce (funk, iterable [, initial]) Where funk is the function on which each element in the iterable gets cumulatively applied to, and initial is the optional value that gets placed before the elements of the iterable in the calculation and serves as a default when the iterable is empty. Properties 101 CU IDOL SELF LEARNING MATERIAL (SLM)

 funk requires two arguments, the first of which is the first element in iterable (if initial is not supplied) and the second element in iterable. If initial is supplied, then it becomes the first argument to funk and the first element in iterable becomes the second element.  reduce \"reduces\" iterable into a single value. Example from functools import reduce numbers = [3, 4, 6, 9, 34, 12] def custom_sum(first, second): return first + second result = reduce(custom_sum, numbers) print(“The sum is”,result) Output The sum is 68 In the above example, reduce takes the first and second elements in numbers and passes them to custom_sum respectively. custom_sum computes their sum and returns it to reduce. reduce then takes that result and applies it as the first element to custom_sum and takes the next element (third) in numbers as the second element to custom_sum. It does this continuously (cumulatively) until numbers is exhausted. 4.11 SUMMARY  A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Function blocks begin with the keyword def followed by the function name and parentheses (()).  A function is recursive if the function calls itself.  Lambda function is an anonymous function that is defined without a name.  Variable-length arguments are arguments that can take an unspecified amount of input.  Functions as first-class citizens where you can pass functions around just like other objects.  Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. 102 CU IDOL SELF LEARNING MATERIAL (SLM)

 Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these arguments from the function call.  Modules refer to a file containing Python statements and definitions.  Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be called and must return the list of attributes 4.12 KEY WORDS  Recursive Function-Function calls itself  Variable Argument-Accepts variable number of arguments  Keyword Argument-Allows change of order of parameters  Lambda Functions-single-line function declared with no name  Optional parameters-Take’s default value if not passed 4.13 LEARNING ACTIVITY 1. Write a Python function that accepts a string and calculate the number of upper-case letters and lower-case letters 2. Write a Python function that takes a list and returns a new list with unique elements of the first list. 3. Write a Python function to check whether a number is perfect or not.In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself. 4.14 UNIT END QUESTIONS 103 CU IDOL SELF LEARNING MATERIAL (SLM)

A.Descriptive Questions Short Questions 1. Specify the syntax of defining a function. 2. What are formal and actual parameters 3. Can a function have variable number of parameters? Justify. 4. When a lambda function is efficient? 5. Does python allows changing the order of parameters being passed to a function? Justify Long Questions 1. Discuss about user defined functions with an example. 2. Explain how a collection can be passed to a function. Give relevant example 3. Discuss about passing variable number of arguments to a user defined function. 4. How map () function can be used for mapping functions? 5. What is a Lambda function? Illustrate with an example. 6. Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument B. Multiple ChoiceQuestions 1.Which of the following is the use of function in python? a. Functions are reusable pieces of programs b. Functions don’t provide better modularity for your application c. you can’t also create your own functions d. All of these 2. Which keyword is used for function? a. Fun b. Define c. Def d. Function 3. What will be the output of the following Python code? 104 def printMax(a, b): if a > b: print(a, 'is maximum') CU IDOL SELF LEARNING MATERIAL (SLM)

elif a == b: 105 print(a, 'is equal to', b) else: print(b, 'is maximum') printMax(3, 4) a. 3 b. 4 c. 4 is maximum d. Error 4. What will be the output of the following Python code? x = 50 def funk(x): print('x is', x) x=2 print('Changed local x to', x) funk(x) print('x is now', x) a. x is 50 Changed local x to 2 x is now 50 b. x is 50 Changed local x to 2 x is now 2 c. x is 50 Changed local x to 2 x is now 100 d. Error 5. What will be the output of the following Python code? x = 50 def funk(): global x print('x is', x) x=2 print('Changed global x to', x) funk() print('Value of x is', x) CU IDOL SELF LEARNING MATERIAL (SLM)

a. x is 50 106 Changed global x to 2 Value of x is 50 b. x is 50 Changed global x to 2 Value of x is 2 c. x is 50 Changed global x to 50 Value of x is 50 d. Error 6. What will be the output of the following Python code? def say(message, times = 1): print(message * times) say('Hello') say('World', 5) a. Hello WorldWorldWorldWorldWorld b. Hello World 5 c. Hello World,World,World,World,World d. Hello HelloHelloHelloHelloHello 7. What will be the output of the following Python code? def funk(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) funk(3, 7) funk(25, c = 24) funk(c = 50, a = 100) a. a is 7 and b is 3 and c is 10 a is 25 and b is 5 and c is 24 b. is 5 and b is 100 and c is 50 a is 3 and b is 7 and c is 10 a is 5 and b is 25 and c is 24 CU IDOL SELF LEARNING MATERIAL (SLM)

a is 50 and b is 100 and c is 5 c. a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50 d. None of these 8. Which of the following is a feature of Docstring? a. Provide a convenient way of associating documentation with Python modules, functions, classes, and methods b. All functions should have a docstring c. Docstrings can be accessed by the __doc__ attribute on objects d. All of these 9. Where is function defined? a. Module b. Class c. Another function d. All of these 10. What will be the output of the following Python code? 107 lamb = lambda x: x ** 3 print(lamb(5)) a. 15 b. 555 c. 125 d. None of these Answers 1 – a, 2- c, 3- c, 4- a, 5- b, 6- a, 7- c, 8- d, 9-d, 10-c CU IDOL SELF LEARNING MATERIAL (SLM)

4.15REFERENCES Text Books:  Allen B. Downey, “Think Python: How to Think likea Computer Scientist”, 2nd edition, Updated for Python 3, Shroff/O ‘Reilly Publishers, 2016  Michael Urban, Joel Murach, Mike Murach: Murach'sPython Programming; Dec, 2016 Reference Books:  Guido van Rossum and Fred L. Drake Jr, An Introduction to Python – Revised and updated for Python 3.2,  Jake VanderPlas, “Python Data Science Handbook”, O ‘Reilly Publishers, 2016. 108 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 5: CLASSES Structure 5.0. Learning Objectives 5.1. Introduction 5.2. Principles of Object Orientation 5.3. Classes in Python 5.3.1 Creating Class 5.3.2 Instance Objects 5.3.3 Access Specifiers 5.3.4 Constructor 5.4. Inheritance 5.5. Python Standard Library 5.6. Summary 5.7. Keywords 5.8. Learning Activity 5.9. Unit End Questions 5.10. References 5.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Outline the concept of object orientation in Python  Illustrate the working of class and objects  Demonstrate the Object Orientation concepts  Familiarize the concept of inheritance and polymorphism 5.1 INTRODUCTION Object-oriented programming is a programming approach that helps you to organise programmes by grouping properties and actions into individual objects. An object, for example, may represent an individual with properties such as a name, age, and address, as well as behaviours such as walking, talking, breathing, and running. Or it could represent an 109 CU IDOL SELF LEARNING MATERIAL (SLM)

email with properties like a recipient list, subject, and body and behaviours like adding attachments and sending. Another words, object-oriented programming is a technique for modelling actual, real-world objects, such as vehicles, as well as relationships between objects, such as businesses and staff, students and instructors, and so on. OOP represents real-world entities as virtual structures that contain data and can execute specific functions. Another common programming paradigm is procedural programming, which structures a program like a recipe in that it provides a set of steps, in the form of functions and code blocks that flow sequentially in order to complete a task. The main takeaway is that objects are fundamental to object-oriented programming in Python, not only in representing data, as in procedural programming, but also in the general structure of the code. 5.2 PRINCIPLES OF OBJECT ORIENTATION Class: A prototype for an object defined by the user that specifies a collection of attributes that describe every object of the class. Attributes are data members (class variables and instance variables) and methods that can be obtained using dot notation. Object: A distinctive instance of a data structure specified by its class. An object is a real- world entity made up of data members (class variables and instance variables) as well as methods. Class variable: A variable that is shared by all instances of a class. Class variables are described within a class but independent of all of its methods. Class variables are not as widely used as instance variables. Data member: A class variable or instance variable that contains information associated with a class and its objects. Function overloading (or) Polymorphism: It is the assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved. Instance variable: A variable specified within a method that is unique to the current instance of a class. Inheritance: The transition of a class's features to other classes that are derived from it. Instance: An individual object of a particular class. An object that belongs to a class Rectangle, for example, is an instance of the class Rectangle. 110 CU IDOL SELF LEARNING MATERIAL (SLM)

Instantiation: The creation of an instance of a class. Method: A type of function that is defined in a class description. Operator overloading: The assignment of several functions to a single operator. Encapsulation: In Python, encapsulation is the act of combining variables and methods into a single object. A class of programming is an example that contains all of the variables and methods specified within it. Encapsulation serves as a security shield by ensuring that no code specified in the class in which the wrapped data are defined can access the wrapped data. Encapsulation provides security by hiding the data from the outside world. 5.3 CLASSES IN PYTHON A class is nothing more than a container for static data members or method statements, which are referred to as a class's attributes. Classes have something that can be thought of as a model for constructing \"true\" objects, known as class instances. Methods are functions that are part of a class. Classes are object-oriented constructs that are not required at this level of Python learning. However, we will present it here for those who have some background in object-oriented methodology and would like to see how classes are implemented in Python. 5.3.1 Creating Class In Python, class definitions begin with the class keyword, just as function definitions do. The first string inside the class is known as the docstring, and it contains a short overview of the class. While not needed, it is strongly advised. Syntax classclass_name[( base_classes_if_any)]: \"optional documentation string\" static_member_declarations method_declarations The class keyword is used to declare classes. When declaring a subclass, the superior base class from which it is inherited is enclosed in parentheses. This line is then accompanied by an optional class documentation string, static member declarations, and any function declarations. Instance methods are functions that are defined inside a class and can only be called from an instance of that class. Just like init__(), an instance method’s first parameter is always self. 111 CU IDOL SELF LEARNING MATERIAL (SLM)

Example: class Employee: 'Common base class for all employees' def __init__(self, name, salary): self.name = name self.salary = salary def displayEmployee(self): print \"Name : \", self.name, \", Salary: \", self.salary When the class is invoked, the instance object is created as the first step in the instantiation process. Once the object is open, a check is performed to see whether a function contructor has been introduced. Without overriding the function constructor, the special procedure __init__, no special actions are taken on the instance by design (). Every special activity that is requested necessarily involves the implementation of __init__(), which overrides the default behaviour. If __init__() is not enforced, the object is returned, and the instantiation process stops. If __init__() is enforced, the special method is called and the instance object is passed in as the first argument (self), much like a regular method call. Any arguments passed to the class invocation call are passed on to __init__(). We can almost visualize the call to build the class as a call to the constructor. __init__() is one of many special methods which can be defined for classes. Some of these special methods are predefined with inaction as their default behaviour (such as __init__()) and must be overridden for customization while others should be implemented on an as-needed basis. Self is basically an instance's handle to itself. When a method is called, self refers to the instance which made the call. No class methods may be called without an instance, and is one reason why self is required. Class methods which belong to an instance are called bound methods. 5.3.2 Instance Objects To create instances of a class, we call the class using class name and pass in whatever arguments its __init__ method accepts. 112 CU IDOL SELF LEARNING MATERIAL (SLM)

Example: \"This would create first object of Employee class\" emp1 = Employee(\"Zara\", 2000) \"This would create second object of Employee class\" emp2 = Employee(\"Manni\", 5000) Accessing Attributes: We access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows emp1.displayEmployee() emp2.displayEmployee() print \"Total Employee \",Employee.empCount Instead of using the normal statements to access attributes, you can use the following functions −  The getattr(obj, name[, default]) − to access the attribute of object.  The hasattr(obj,name) − to check if an attribute exists or not.  The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.  The delattr(obj, name) − to delete an attribute. Built-In Class Attributes Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −  __dict__ Dictionary containing the class's namespace.  __doc__ Class documentation string or none, if undefined.  __name__ Class name.  __module__ Module name in which the class is defined. This attribute is \"__main__\" in interactive mode.  __bases__ A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list. 113 CU IDOL SELF LEARNING MATERIAL (SLM)

Example Program with Class and Objects class Person: def __init__(self, name, age): self.name = name self.age = age #instance method to display name def myfunc(self): print(\"Hello my name is \" + self.name) # creating object to class Person p1 = Person(\"John\", 36) #Accessing methods of class Person using object p1.myfunc() Output: Hello my name is John 5.3.3 Access Specifiers Python control access changes are used to limit access to the class's variables and procedures. Python employs the ‘_' symbol to specify the access control for a particular data member or member feature of a class. Python access specifiers play an important role in protecting data from unwanted access and stopping it from being abused. A Class in Python has three types of access modifiers:  Public Access Modifier  Protected Access Modifier  Private Access Modifier Public Access Modifier Members in a class that have been made public can be accessed from any section of the code. By default, all data members and member functions of a class are public. 114 CU IDOL SELF LEARNING MATERIAL (SLM)

class Student: # constructor def __init__(self, name, age): # public data members self. StudentName = name self.StudentAge = age # public memeber function def displayAge(self): # accessing public data member print(\"Age: \", self. self.StudentAge) # creating object of the class obj = Geek(\"Virat\", 20) # accessing public data member print(\"Name: \", StudentName) # calling public member function of the class obj.displayAge() Output: Virat 20 In the above program, StudentName and StudentAge are public data members and displayAge() method is a public member function of the class Student. These data members of the class Student can be accessed from anywhere in the program. Protected Access Modifier The members of a class that are declared protected are only accessible to a class derived from it. Data members of a class are declared protected by adding a single underscore ‘_’ symbol before the data member of that class. 115 CU IDOL SELF LEARNING MATERIAL (SLM)

# program to illustrate protected access modifier in a class 116 class Student: # protected data members _name = None _roll = None _branch = None # constructor def __init__(self, name, roll, branch): self._name = name self._roll = roll self._branch = branch # protected member function def _displayRollAndBranch(self): # accessing protected data members print(\"Roll: \", self._roll) print(\"Branch: \", self._branch) # derived class classStud(Student): # constructor def __init__(self, name, roll, branch): Student.__init__(self, name, roll, branch) # public member function def displayDetails(self): # accessing protected data members of super class print(\"Name: \", self._name) # accessing protected member functions of super class self._displayRollAndBranch() # creating objects of the derived class obj = Stud(\"John\", 1706256, \"Information Technology\") # calling public member functions of the class obj.displayDetails() CU IDOL SELF LEARNING MATERIAL (SLM)

Output: Name: John Roll: 1706256 Branch: Information Technology In the above program, _name, _roll and _branch are protected data members and _displayRollAndBranch() method is a protected method of the super class Student. The displayDetails() method is a public member function of the class Stud which is derived from the Student class, the displayDetails() method in Stud class accesses the protected data members of the Student class. Private Access Modifier The members of a class that are declared private are accessible within the class only, private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class. 117 CU IDOL SELF LEARNING MATERIAL (SLM)

classStudent: __name = None __roll = None __branch = None # constructor def __init__(self, name, roll, branch): self.__name = name self.__roll = roll self.__branch = branch # private member function def __displayDetails(self): # accessing private data members print(\"Name: \", self.__name) print(\"Roll: \", self.__roll) print(\"Branch: \", self.__branch) # public member function def accessPrivateFunction(self): # accesing private member function self.__displayDetails() # creating object obj = Student (\"John\", 1706256, \"Information Technology\") # calling public member function of the class obj.accessPrivateFunction() Output. Name: John Roll: 1706256 Branch: Information Technology In the above program, _name, _roll and _branch are private members, __displayDetails() method is a private member function (these can only be accessed within the class) and accessPrivateFunction() method is a public member function 118 CU IDOL SELF LEARNING MATERIAL (SLM)

of the class Student which can be accessed from anywhere within the program. The accessPrivateFunction() method accesses the private members of the class Student. program to illustrate access modifiers of a class # super class class Super: # public data member var1 = None # protected data member _var2 = None # private data member __var3 = None # constructor def __init__(self, var1, var2, var3): self.var1 = var1 self._var2 = var2 self.__var3 = var3 119 CU IDOL SELF LEARNING MATERIAL (SLM)

# public member function def displayPublicMembers(self): # accessing public data members print(\"Public Data Member: \", self.var1) # protected member function def _displayProtectedMembers(self): # accessing protected data members print(\"Protected Data Member: \", self._var2) # private member function def __displayPrivateMembers(self): # accessing private data members print(\"Private Data Member: \", self.__var3) # public member function def accessPrivateMembers(self): # accessing private memeber function self.__displayPrivateMembers() # derived class class Sub(Super): # constructor def __init__(self, var1, var2, var3): Super.__init__(self, var1, var2, var3) # public member function def accessProtectedMemebers(self): # accessing protected member functions of super class self. DisplayProtectedMembers() # creating objects of the derived class obj = Sub(\"John\", 4, \"IT\") # calling public member functions of the class obj.displayPublicMembers() obj.accessProtectedMemebers() obj.accessPrivateMembers() 120 CU IDOL SELF LEARNING MATERIAL (SLM)

# Object can access protected member print(\"Object is accessing protected member:\", obj._var2) # object cannot access private member, so it will generate Attribute error #print(obj.__var3) Output Public Data Member: John Protected Data Member: 4 Private Data Member: IT In the above program, the accessProtectedMemebers() method is a public member function of the class Sub accesses the _displayProtectedMembers() method which is protected member function of the class Super and the accessPrivateMembers() method is a public member function of the class Super which accesses the __displayPrivateMembers() method which is a private member function of the class Super. 5.3.4 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. Non-Parameterized Constructor 2. Parameterized Constructor 3. Default 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. 121 CU IDOL SELF LEARNING MATERIAL (SLM)

Consider the following example to initialize the Employee class attributes. 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) emp1.display() emp2.display() OUTPUT: ID: 101 Name: John ID: 102 Name: David Non-Parameterized Constructor This constructor doesn’t accept any arguments. It does not perform any task but initializes the objects. It has only self as an argument 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\") Parameterized Constructor Constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer. 122 CU IDOL SELF LEARNING MATERIAL (SLM)

1. class Student: 2. # Constructor - parameterized 3. def __init__(self, name): 4. print(\"This is parametrized constructor\") 5. self.name = name 6. def show(self): 7. print(\"Hello\",self.name) 8. student = Student(\"John\") 9. student.show() Output This is parametrized constructor Hello John Default Constructor An object cannot be created if we don’t have a constructor in our program. This is why when we do not declare a constructor in our program, python does it for us. It does not perform any task but initializes the objects. class Student: roll_num = 101 name = \"Joseph\" def display(self): print(self.roll_num,self.name) st = Student() st.display() Output: 101 Joseph Built-in Class Functions The built-in functions defined in the class are described in the following table. 123 CU IDOL SELF LEARNING MATERIAL (SLM)

S.No Function Description 1 getattr(obj,name,default) It is used to access the attribute of the object. 2 It is used to set a particular value to the specific setattr(obj, name,value) attribute of an object. 3 delattr(obj, name) It is used to delete a specific attribute. 4 It returns true if the object contains some specific hasattr(obj, name) attribute. Table 5.1 Built-in Class Functions in Python 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. SN Attribute Description 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. Table 5.2 Built-in Class Attributes in Python 124 CU IDOL SELF LEARNING MATERIAL (SLM)

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__ 5.4INHERITANCE Inheritance refers to the capability of a class to inherit or derive properties or characteristics other class. It is very important feature of object-oriented program as it allows reusability i.e., using a method defined in another class by using inheritance. The class that derives properties from other class is known as child class or subclass and the class from which the properties are inherited is base class or parent class. Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name Syntax class Subclass Name (ParentClass1[, ParentClass2, ...]): \"Optional class documentation string\" class suite 125 CU IDOL SELF LEARNING MATERIAL (SLM)

Example class Parent: # define parent class parentAttr = 100 def __init__(self): print \"Calling parent constructor\" def parentMethod(self): print \"Calling parent method\" def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print \"Parent attribute :\", Parent.parentAttr class Child(Parent): # define child class def __init__(self): print \"Calling child constructor\" def childMethod(self): print \"Calling child method\" c = Child() # instance of child c.childMethod() # child calls its method c.parentMethod() # calls parent's method c.setAttr(200) # again call parent's method c.getAttr() # again call parent's method Output Calling child constructor Calling child method Calling parent method Parent attribute: 200 We can use issubclass() or isinstance() functions to check a relationship of two classes and instances. The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup. 126 CU IDOL SELF LEARNING MATERIAL (SLM)

The isinstance(obj, Class) boolean function returns true if obj is an instance of Class or is an instance of a subclass of Class. Example # parent class class Bird: def __init__(self): print(\"Bird is ready\") def whoisThis(self): print(\"Bird\") def swim(self): print(\"Swim faster\") # child class class Penguin(Bird): def __init__(self): # call super() function super().__init__() print(\"Penguin is ready\") def whoisThis(self): print(\"Penguin\") def run(self): print(\"Run faster\") #creating objects peggy = Penguin() peggy.whoisThis() peggy.swim() peggy.run() Output: 127 Bird is ready Penguin is ready Penguin Swim faster Run faster CU IDOL SELF LEARNING MATERIAL (SLM)

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The child class inherits the functions of parent class. We can see this from the swim() method. Again, the child class modified the behaviour of the parent class. We can see this from the whoisThis() method. Furthermore, we extend the functions of the parent class, by creating a new run() method. Additionally, we use the super() function inside the __init__() method. This allows us to run the __init__() method of the parent class inside the child class. Types of Inheritance Based number of child and parent classes involved in the inheritance, there are four types of inheritance in Python. Single Inheritance: Single inheritance enables a derived class to inherit properties from a single parent class, thus enabling code reusability and the addition of new features to existing code. Fig 5.1 Single Inheritance 128 CU IDOL SELF LEARNING MATERIAL (SLM)

Example: # Python program to demonstrate single inheritance # Base class class Parent: def func1(self): print(\"This function is in parent class.\") # Derived class class Child(Parent): def func2(self): print(\"This function is in child class.\") # Driver's code object = Child() object.func1() object.func2() Output: This function is in parent class. This function is in child class. Multiple Inheritance: When a class can be derived from more than one base class this type of inheritance is called multiple inheritance. In multiple inheritance, all the features of the base classes are inherited into the derived class. Fig 5.2 Multiple Inheritance 129 CU IDOL SELF LEARNING MATERIAL (SLM)

Example # Python program to demonstrate multiple inheritance # Base class1 class Mother: mothername = \"\" def mother(self): print(self.mothername) # Base class2 class Father: fathername = \"\" def father(self): print(self.fathername) # Derived class class Son(Mother, Father): def parents(self): print(\"Father :\", self.fathername) print(\"Mother :\", self.mothername) # Driver's code s1 = Son() s1.fathername = \"RAM\" s1.mothername = \"SITA\" s1.parents() Output: Father : RAM Mother : SITA Multilevel Inheritance: In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and grandfather. 130 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 5.3 Multilevel Inheritance # Python program to demonstrate multilevel inheritance # Base class class Grandfather: def __init__(self, grandfathername): self. Grandfathername = grandfathername # Intermediate class class Father(Grandfather): def __init__(self, fathername, grandfathername): self.fathername = fathername # invoking constructor of Grandfather class Grandfather.__init__(self, grandfathername) # Derived class class Son(Father): def __init__(self,sonname, fathername, grandfathername): self.sonname = sonname # invoking constructor of Father class Father.__init__(self, fathername, grandfathername) def print_name(self): print('Grandfather name :', self.grandfathername) print(\"Father name :\", self.fathername) print(\"Son name :\", self.sonname) 131 CU IDOL SELF LEARNING MATERIAL (SLM)

# Driver code s1 = Son('Prince', 'Rampal', 'Lal mani') print(s1.grandfathername) s1.print_name() Output: Lal mani Grandfather name : Lal mani Father name :Rampal Son name : Prince Hierarchical Inheritance: When more than one derived classes are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes. Fig 5.4 Hierarchical Inheritance 132 # Python program to demonstrate Hierarchical inheritance # Base class class Parent: def func1(self): print(\"This function is in parent class.\") # Derived class1 class Child1(Parent): def func2(self): print(\"This function is in child 1.\") # Derived class2 class Child2(Parent): def func3(self): print(\"This function is in child 2.\") CU IDOL SELF LEARNING MATERIAL (SLM) # Driver's code object1 = Child1()

# Derived class2 class Child2(Parent): def func3(self): print(\"This function is in child 2.\") # Driver's code object1 = Child1() object2 = Child2() object1.func1() object1.func2() object2.func1() object2.func3() Output: This function is in parent class. This function is in child 1. This function is in parent class. This function is in child 2. Hybrid Inheritance: Inheritance consisting of multiple types of inheritance is called hybrid inheritance. We may use any combination as a single with multiple inheritances, multi-level with multiple inheritances, etc. 5.5 PYTHON STANDARD LIBRARY Python’s standard library is very extensive, offering a wide range of facilities as indicated by the long table of contents listed below. The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs. The Python installers for the Windows platform usually include the entire standard library and often also include many additional components. For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packaging tools provided with the operating system to obtain some or all of the optional components. 133 CU IDOL SELF LEARNING MATERIAL (SLM)

5.6 SUMMARY  Python is an object-oriented programming language.  An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values.  Python control access modifications which are used to restrict access to the variables and methods of the class  Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.  Polymorphism is the ability of different objects to respond in a unique way to the same message. Polymorphism is achieved by method overriding and operator overloading.  Type ( ) is used to find the type of variable used in the program in the runtime.  Run time errors can be handled using exception handling mechanism 5.7 KEY WORDS  Classes-code template for creating objects  Object-real world entity  Constructor-used for instantiating an object  Inheritance-inherits all the methods and properties from another class  Standard Library-collection of script modules accessible to a Python program 5.8 LEARNING ACTIVITY 1. Write a Python program to create two empty classes, Student and Marks. Now create some instances and check whether they are instances of the said classes or not. Also, check whether the said classes are subclasses of the built-in object class or not. 2. Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle. 134 CU IDOL SELF LEARNING MATERIAL (SLM)

5.9UNIT END QUESTIONS A. Descriptive Type Questions Short Questions 1. Define Class and Object. 2. How is polymorphism achieved in python? 3. Specify the syntax of type() function. 4. List the benefits of inheritance. 5. Show how a constructor is created in python. Long Questions 1. List the features and explain about different Object-Oriented features supported by Python. 2. Describe the concept of method overriding with an example. 3. How to declare a constructor method in python? Explain. 4. Explain the feature of Inheritance in python with an example. 5. Write a Python class named Rectangle constructed by a length and width and a method which will compute the area of a rectangle. B. Multiple Choice Questions 1. What will be the output of the following Python code? class change: def __init__(self, x, y, z): self.a = x + y + z x = change(1,2,3) y = getattr(x, 'a') setattr(x, 'a', y+1) print(x.a) a. 6 b. 7 c. Error d. 0 2. What will be the output of the following Python code? 135 class test: CU IDOL SELF LEARNING MATERIAL (SLM)

def __init__(self,a): 136 self.a=a def display(self): print(self.a) obj=test() obj.display() a. Runs normally, doesn’t display anything b. Displays 0, which is the automatic default value c. Error as one argument is required while creating the object d. Error as display function requires additional argument 3. What will be the output of the following Python code? class test: def __init__(self): self.variable = 'Old' self.Change(self.variable) def Change(self, var): var = 'New' obj=test() print(obj.variable) a. Error because function change can’t be called in the __init__ function b. ‘New’ is printed c. ‘Old’ is printed d. Nothing is printed 4. What is Instantiation in terms of OOP terminology? a. Deleting an instance of class b. Modifying an instance of class c. Copying an instance of class d. Creating an instance of class 5. What will be the output of the following Python code? class fruits: def __init__(self, price): CU IDOL SELF LEARNING MATERIAL (SLM)

self.price = price obj=fruits(50) obj.quantity=10 obj.bags=2 print(obj.quantity+len(obj.__dict__)) a. 12 b. 52 c. 13 d. 60 6. What will be the output of the following Python code? class Demo: def __init__(self): pass def test(self): print(__name__) obj = Demo() obj.test() a. Exception is thrown b. __main__ c. Demo d. Test Answers 1- b, 2- c, 3- c, 4- d, 5-c, 6- b 5.10REFERENCES Text Books:  Allen B. Downey, “Think Python: How to Think likea Computer Scientist”, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016  Michael Urban, Joel Murach, Mike Murach: Murach'sPython Programming; Dec, 2016 Reference Books: 137 CU IDOL SELF LEARNING MATERIAL (SLM)

 Guido van Rossum and Fred L. Drake Jr, An Introduction to Python – Revised and updated for Python 3.2,  Jake VanderPlas, “Python Data Science Handbook”, O‘Reilly Publishers, 2016. 138 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 6: PYTHON FOR DATA ANALYSIS AND VISUALIZATION 1 Structure 6.0. LearningObjectives 6.1. Introduction 6.2. Numeric Operations on Numpy 6.3. Plotting Data from Numpy 6.4. Summary 6.5. Keywords 6.6. Learning Activity 6.7. Unit End Questions 6.8. References 6.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe the basics of numpy  Identify the key terminologies of data visualization  Familiarize plotting graph for visualization 6.1 INTRODUCTION NumPy (short for Numerical Python) provides an efficient interface to store and operate on dense data buffers. In some ways, NumPy arrays are like Python’s built-in list type, but NumPy arrays provide much more efficient storage and data operations as the arrays grow larger in size. NumPy arrays form the core of nearly the entire ecosystem of data science tools in Python Fixed-Type Arrays in Python Python offers several different options for storing data in efficient, fixed-type data buffers. The built-in array module (available since Python 3.3) can be used to create dense arrays of a uniform type: 139 CU IDOL SELF LEARNING MATERIAL (SLM)

In[6]: import array L = list(range(10)) A = array.array('i', L) A Out[6]: array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Here 'i' is a type code indicating the contents are integers. Much more useful, however, is the ndarray object of the NumPy package. While Python’s array object provides efficient storage of array-based data, NumPy adds to this efficient operation on that data. We will explore these operations in later sections; here we’ll demonstrate several ways of creating a NumPy array. Creating Arrays from Python Lists First, we can use np.array to create arrays from Python lists: In[8]: # integer array: np.array([1, 4, 2, 5, 3]) Out[8]: array([1, 4, 2, 5, 3]) NumPy is constrained to arrays that all contain the same type. If types do not match, NumPy will upcast if possible (here, integers are upcast to floating point): In[9]: np.array([3.14, 4, 2, 3]) Out[9]: array([ 3.14, 4. , 2. , 3. ]) If we want to explicitly set the data type of the resulting array, we can use the dtype keyword: In[10]: np.array([1, 2, 3, 4], dtype='float32') Out[10]: array([ 1., 2., 3., 4.], dtype=float32) Finally, unlike Python lists, NumPy arrays can explicitly be multidimensional; here’s one way of initializing a multidimensional array using a list of lists: In[11]: # nested lists result in multidimensional arrays np.array([range(i, i + 3) for i in [2, 4, 6]]) Out[11]: array([[2, 3, 4], 140 CU IDOL SELF LEARNING MATERIAL (SLM)

[4, 5, 6], [6, 7, 8]]) The inner lists are treated as rows of the resulting two-dimensional array. NumPy Standard Data Types NumPy arrays contain values of a single type, so it is important to have detailed knowledge of those types and their limitations. Because NumPy is built in C, the types will be familiar to users of C, Fortran, and other related languages. Figure 6.1 Standard Numpy Data types Numpy Arrays Data manipulation in Python is nearly synonymous with NumPy array manipulation. Numpy array is a powerful N-dimensional array object which is in the form of rows and columns. We can initialize NumPy arrays from nested Python lists and access it elements. A Numpy array on a structural level is made up of a combination of:  The Data pointer indicates the memory address of the first byte in the array.  The Data type or dtype pointer describes the kind of elements that are contained 141 CU IDOL SELF LEARNING MATERIAL (SLM)

within the array.  The shape indicates the shape of the array.  The strides are the number of bytes that should be skipped in memory to go to the next element. Numpy Array Attributes A NumPy array object has a number of attributes, which help in giving information about the array. Here are its important attributes: >>> import numpy as np >>>n_array = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) • ndim: This gives the number of dimensions of the array. T The following shows that the array that we defined had two dimensions: >>>n_array.ndim 2 n_array has a rank of 2, which is a 2D array. • shape: This gives the size of each dimension of the array: >>>n_array.shape (3, 4) The first dimension of n_array has a size of 3 and the second dimension has a size of 4. This can be also visualized as three rows and four columns. • size: This gives the number of elements: >>>n_array.size 12 The total number of elements in n_array is 12. • dtype: This gives the datatype of the elements in the array: >>> n_array.dtype.name 142 CU IDOL SELF LEARNING MATERIAL (SLM)

int64 The number is stored as int64 in n_array. 6.2NUMERIC OPERATIONS ON NUMPY Arithmetic Operations Input arrays for performing arithmetic operations such as add(), subtract(), multiply(), and divide() must be either of the same shape or should conform to array broadcasting rules. mportnumpy as np a = np.arange(9, dtype = np.float_).reshape(3,3) print 'First array:' print a print '\\n' print 'Second array:' b = np.array([10,10,10]) print b print '\\n' print 'Add the two arrays:' printnp.add(a,b) print '\\n' print 'Subtract the two arrays:' printnp.subtract(a,b) print '\\n' print 'Multiply the two arrays:' printnp.multiply(a,b) print '\\n' print 'Divide the two arrays:' printnp.divide(a,b) 143 CU IDOL SELF LEARNING MATERIAL (SLM)

Output: First array: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Second array: [10 10 10] Add the two arrays: [[ 10. 11. 12.] [ 13. 14. 15.] [ 16. 17. 18.]] Subtract the two arrays: [[-10. -9. -8.] [ -7. -6. -5.] [ -4. -3. -2.]] Multiply the two arrays: [[ 0. 10. 20.] [ 30. 40. 50.] [ 60. 70. 80.]] Divide the two arrays: [[ 0. 0.1 0.2] [ 0.3 0.4 0.5] [ 0.6 0.7 0.8]] numpy.reciprocol() This function returns the reciprocal of argument, elementwise. For elements with absolute values larger than 1, the result is always 0 and for integer 0, overflow warning is issued. 144 CU IDOL SELF LEARNING MATERIAL (SLM)

# Python code to perform reciprocal operation # on NumPy array import numpy as np arr = np.array([25, 1.33, 1, 1, 100]) print('Our array is:') print(arr) print('\\nAfter applying reciprocal function:') print(np.reciprocal(arr)) arr2 = np.array([25], dtype = int) print('\\nThe second array is:') print(arr2) print('\\nAfter applying reciprocal function:') print(np.reciprocal(arr2)) Output Our array is: [ 25. 1.33 1. 1. 100. ] After applying reciprocal function: [ 0.04 0.7518797 1. 1. 0.01 ] The second array is: [25] After applying reciprocal function: [0] numpy.power() This function treats elements in the first input array as the base and returns it raised to the power of the corresponding element in the second input array. # Python code to perform power operation 145 CU IDOL SELF LEARNING MATERIAL (SLM)

# onNumPy array importnumpy as np arr = np.array([5, 10, 15]) print('First array is:') print(arr) print('\\nApplying power function:') print(np.power(arr, 2)) print('\\nSecond array is:') arr1 = np.array([1, 2, 3]) print(arr1) print('\\nApplying power function again:') print(np.power(arr, arr1)) Output First array is: [ 5 10 15] Applying power function: [ 25 100 225] Second array is: [1 2 3] Applying power function again: [ 5 100 3375] numpy.mod() This function returns the remainder of division of the corresponding elements in the input array. The function numpy.remainder() also produces the same result. # Python code to perform mod function # onNumPy array 146 CU IDOL SELF LEARNING MATERIAL (SLM)

importnumpy as np arr = np.array([5, 15, 20]) arr1 = np.array([2, 5, 9]) print('First array:') print(arr) print('\\nSecond array:') print(arr1) print('\\nApplying mod() function:') print(np.mod(arr, arr1)) print('\\nApplying remainder() function:') print(np.remainder(arr, arr1)) Output First array: [ 5 15 20] Second array: [2 5 9] Applying mod() function: [1 0 2] Applying remainder() function: [1 0 2] 147 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 6.2 Arithmetic operations implemented in numpy 6.3PLOTTING DATA FROM NUMPY Visualization is a very integral part of data science. It helps in communicating a pattern or a relationship that cannot be seen by looking at raw data. It's easier for a person to remember a picture and recollect it as compared to lines of text. This holds true for data too Matplotlib is a plotting library for Python. It is used along with NumPy to provide an environment that is an effective open-source alternative for MATLAB. It can also be used with graphics toolkits like PyQt and wxPython. Matplotlib module was first written by John D. Hunter. Since 2012, Michael Droettboom is the principal developer. Currently, Matplotlib ver. 1.5.1 is the stable version available. The package is available in binary distribution as well as in the source code form on www.matplotlib.org. Conventionally, the package is imported into the Python script by adding the following statement − Frommatplotlib import pyplot as plt Here pyplot() is the most important function in matplotlib library, which is used to plot 2D data. The following script plots the equation y = 2x + 5 importnumpy as np frommatplotlib import pyplot as plt x = np.arange(1,11) y=2*x+5 plt.title(\"Matplotlib demo\") plt.xlabel(\"x axis caption\") plt.ylabel(\"y axis caption\") plt.plot(x,y) plt.show() An ndarray object x is created from np.arange() function as the values on the x axis. The corresponding values on the y axis are stored in another ndarray object y. These values are plotted using plot() function of pyplot submodule of matplotlib package. 148 CU IDOL SELF LEARNING MATERIAL (SLM)

The graphical representation is displayed by show() function. Line Colors and Styles The first adjustment you might wish to make to a plot is to control the line colors and styles. The plt.plot() function takes additional arguments that can be used to specify these. To adjust the color, you can use the color keyword, which accepts a string argument representing virtually any imaginable color. In[6]: plt.plot(x, np.sin(x - 0), color='blue') # specify color by name plt.plot(x, np.sin(x - 1), color='g') # short color code (rgbcmyk) plt.plot(x, np.sin(x - 2), color='0.75') # Grayscale between 0 and 1 plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF) plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 and 1 plt.plot(x, np.sin(x - 5), color='chartreuse'); # all HTML color names supported Figure6.3: Colors in Plot 149 CU IDOL SELF LEARNING MATERIAL (SLM)

If no color is specified, Matplotlib will automatically cycle through a set of default colors for multiple lines. Similarly, you can adjust the line style using the linestyle keyword \\In[7]: plt.plot(x, x + 0, linestyle='solid') plt.plot(x, x + 1, linestyle='dashed') plt.plot(x, x + 2, linestyle='dashdot') plt.plot(x, x + 3, linestyle='dotted'); # For short, you can use the following codes: plt.plot(x, x + 4, linestyle='-') # solid plt.plot(x, x + 5, linestyle='--') # dashed plt.plot(x, x + 6, linestyle='-.') # dashdot plt.plot(x, x + 7, linestyle=':'); # dotted Figure 6.4: Line Styles in Plot Axes Limits Matplotlib does a decent job of choosing default axes limits for your plot, but some‐ times it’s nice to have finer control. The most basic way to adjust axis limits is to use the plt.xlim() and plt.ylim() methods In[9]: plt.plot(x, np.sin(x)) plt.xlim(-1, 11) plt.ylim(-1.5, 1.5); 150 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook