Tuesday, 17 November 2020

PYTHON-Course-Classes and Object-oriented Programming


 PYTHON-Classes and Object-oriented Programming

A user-defined prototype for an object that defines a set of attributes that characterize any object of the class.

The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.

 OOP Terminology Class:

Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.

Data member − A class variable or instance variable that holds data associated with a class and its objects.

Function overloading − The assignment of more than one behaviour to a particular function. The operation performed varies by the types of objects or arguments involved.

 Instance variable – A variable that is defined inside a method and belongs only to the current instance of a class.  

Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.  

Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.

 Method − A special kind of function that is defined in a class definition.

 Object − A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.

 Operator overloading − The assignment of more than one function to a particular operator.


 #Class Constructor Function class Employee: #Common base class for all employees empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" ,Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary #Creating Instance Object emp1 = Employee("Zara", 2000) emp2 = Employee("Manni", 5000) #Accessing Object emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class. To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts. You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows −

class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print ("Total Employee %d" % Employee.empCount) def displayEmployee(self): print ("Name : ", self.name, ", Salary: ", self.salary) "This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print ("Total Employee %d" % Employee.empCount)

 Calc Via Class class cal(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b def mul(self): return self.a*self.b def div(self): return self.a/self.b def sub(self): return self.a-self.b a=int(input("Enter first number: ")) b=int(input("Enter second number: ")) obj=cal(a,b) choice=1 while choice!=0: print("0. Exit") print("1. Add") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice=int(input("Enter choice: ")) if choice==1: print("Result: ",obj.add()) elif choice==2: print("Result: ",obj.sub()) elif choice==3: print("Result: ",obj.mul()) elif choice==4: print("Result: ",round(obj.div(),2)) elif choice==0: print("Exiting!") else: print("Invalid choice!!") print()

 Built-In Class Attributes Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other

Destroying Objects (Garbage Collection) / Destruction :

 Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.

Python's garbage collector It runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.

 You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.

class Point: def __init__( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print (class_name, "destroyed") pt1 = Point() pt2 = pt1 pt3 = pt1 print (id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts del pt1 del pt2 del pt3

Class Inheritance:  Instead of starting from scratch, you can create a class by deriving it from a pre-existing class by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

Syntax Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name − class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string‘

Get And SET Attribute Get and set attribute of objects. The syntax of setattr() method is: 

setattr(object, name, value) setattr() Parameters The setattr() method takes three parameters

object - object whose attribute has to be set .

 name - string which contains the name of the attribute to be set

 value - value of the attribute to be set


class Person: name = 'Adam' p = Person() print('Before modification:', p.name) # setting name to 'John‘ setattr(p, 'name', 'John') print('After modification:', p.name) #Mainly GET and SET used for …. class Person: name = 'Adam' p = Person() # setting attribute name to None setattr(p, 'name', None) print('Name is:', p.name) # setting an attribute not present # in Person setattr(p, 'age', 23) print('Age is:', p.age)

 Get Attribute The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

The syntax of getattr() method is: getattr(object, name[, default]) getattr() Parameters The getattr() method takes multiple parameters:

 object - object whose named attribute's value is to be returned

name - string that contains the attribute's name

default (Optional) - value that is returned when the named attribute is not found

#E.G. class Person: age = 23 name = "Adam“ person = Person() # when default value is provided print('The gender is:', getattr(person, 'gender', 'Male')) # when no default value is provided print('The gender is:', getattr(person, 'gender'))


 #Inheritance 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

Overriding Methods - You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass. 

 Example class Parent: # define parent class def myMethod(self): print ('Calling parent method vadil') class Child(Parent): # define child class def myMethod(self): print ('Calling child method 6okrav') c = Child() # instance of child c.myMethod() # child calls overridden method.


What is MRO :

 A class can be derived from more than one base classes in Python. This is called multiple inheritance.

 In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.

 E.g.. class Super1: pass class, Super2: pass class

    MultiDerived(Super1, Super2): pass - In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching same class twice. - MRO Stand for Method resolution Order.So, in the above example of MultiDerived class the search order is [MultiDerived, Super1, Super2, object]. This order is also called linearization of MultiDerived class and the set of rules used to find this order is called Method Resolution Order (MRO).

 MRO ensures that a class always appears before its parents and in case of multiple parents, the order is same as tuple of base classes.


Duck Typing : Duck typing is a concept that says that the “type” of the object is a matter of concern only at runtime and you don’t need to to explicitly mention the type of the object before you perform nay kind of operation on that object.

 You don’t need to define the type of things like int,float etc…its called duck typing.

 The following example can help in understanding this concept –

def calc(a,b):

 return a+b

                Method Overloading : Same name different arguments in method that is called an method overloading.

Python doesn’t support method overloading but if we want to do then we can do as per below. ###

Error def product(a, b): p = a * b print(p) def product(a, b, c): p = a * b*c print(p) #product(4, 5) product(4, 5, 5)

 It’s Work If Different Arguments as a Parameter # Function to take multiple arguments def add(datatype, *args): # if datatype is int # initialize answer as 0 if datatype =='int': answer = 0 # if datatype is str # initialize answer as '' if datatype =='str': answer ='' # Traverse through the arguments for x in args: # This will do addition if the # arguments are int. Or concatenation # if the arguments are str answer = answer + x print(answer) # Integer add('int', 5, 6) # String add('str', 'Hi ', 'Geeks')

 Abstract Class Force a class to implement methods. Abstract classes can contain abstract methods: methods without an implementation. Objects cannot be created from an abstract class. A subclass can implement an abstract class. Meaning of @ This shows that the function/method/class you're defining after a decorator is just basically passed on as an argument to the function/method immediately after the @ sign.

What is __MetaClass__:import abc class AbstractAnimal(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def walk(self): ''' data ''' @abc.abstractmethod def talk(self): ''' data ''' class Duck(AbstractAnimal): name = '' def __init__(self, name): print('duck created.') self.name = name def walk(self): print('walks') def talk(self): print('quack') obj = Duck('duck1') obj.talk() obj.walk()

ABOUT PYTHON

INTRODUCTION:

Like Other Programming Languages like C programming, It is concern with functional aspect.

 We are concerning with writing code using function.

 Programming will become easy if it based on real life example, hence they develop Object Oriented Language like Java and .NET where programming done with Classes and Objects.

 Java Program to Write sum of two numbers

 C program to write sum of two numbers • Python style • a=b=10 • print(“sum”,(a+b))

 

HISTORY of PYTHON:-

 Python was developed by Guido Van Rossum in year 1991, at center for mathematics and Computer science managed by Dutch Govt. Developer was working on project to develop system utilities in C where he had interact with bourn shell available in UNIX.  Python name appeared from the TV Show Monty Python’s Flying Circus  Official launched on 20th Feb 1991.  Python is Open Source.

FEATURES OF PYTHON:- Simple  Easy to learn  Open Source  High level Language  Dynamically Typed  Platform Independence  Portable  procedure and Object oriented

Simple-Python is simple programing Language .felt like reading English sentences. It means more clarity and less stress on understating of syntax of language

 Easy to learn– uses very few keyword , program structure is simple. Similar to C programing . Hence Migration from C to Python is easy for programmers.

 Open Source - easily available for download www.python.org

 High level Language – Similar to English Language , low level language Machine understandable code.

 Dynamically Typed-in - Python , we are not declaring anything. an assignment statement binds a name to an objects can be of any type. If a name is assigned to an objects of one type, it may be later be assigned to an objects of different type.

 >>>year = 2017  >>> dec = 1.1  >>> hello = 'Hello, World!'  >>> alphabet = ['a','b','c']


As you can see, I didn’t have to tell Python what ‘type’ each variable value was, it assigned the types dynamically  Platform Independent-  Portable  Procedure and OOPS based.

Class is collection of objects having similar attributes and operation.  

Python Packages: 

Boto: It is amazon web services  CherryPy is Object oriented HTTP framework  Fiona reads and write big data files. Mysql-connector –python is driver written in python to connect to MySQL database

Numpy- It is a package for processing array of single or multidimensional type  Pandas is package for powerful data structure for data analysis, time series and statistics  Pillow is python imaging library.

Pyquery- represent jquery like library for python.  W3lib is library of web related function.

 

EXECUTION OF PYTHON PROGRAM:- Python program can write in abc.py where abc is name of the program wheras .py is extension name.  Compile the program into python compiler.  Byte code.  Abc.pyc   Pvm  machinecode  result

C VS PYTHON:  Python Programing C program execute Faster Slower compared to C Type Declaration Compulsory Not required C language type discipline in static and weak Python type discipline is dynamic and Strong Pointers available No Pointers C ha s switch statements No switch statement Memory allocation using malloc and calloc Memory allocation and De-allocation done by PVM Procedural approach Oops based.

 JAVA VS PYTHON JAVA PYTHON:  Memory allocation and de-allocation done by JVM PVM Switch is allowed No switch A semicolon is used to terminate the statement and comma is used to separate expression. New line indicate end of statement and semicolon is used as an expression separator Array index is positive integer Can be positive or negative. Static and weak Dynamic and strong Oops languages, functional programming used in java 8.0 in lamda expression Oops language, blends functional programming with lambda expression inbuild.

PVM:-  Python source file converted in Byte Code format.

 Byte code represent the fixed set of instruction created by python developers representing all types of operations.  And store that file in .pyc extension

 Role of PVM to convert that byte code into machine understandable code, so that computer can execute that machine code and display result.  To carry out this conversion , byte code into machine code and sends that machine code to computer processor for execution. Since Interpreter plays main role, often pvm also mention as interpreter.

 FROZEN BINARIES:- Frozen binary executables are packages that combine your program's byte code and the Python interpreter into a single executable program. With these, programs can be launched in the same ways that you would launch any other executable program (icon clicks, command lines, etc.).  py2exe

MEMORY MANAGEMENT IN PYTHON:- Python , memory allocation and de-allocation are done during runtime automatically.  The programmer need not allocate memory while creating objects or deallocate memory when deleting the objects. Python PVM take care of such issues.  Everything is consider as an objects in Python. Example Strings are objects, list are objects , functions are objects. For every object, memory should be allocated .memory manager inside PVM allocates memory required for the objects created in Python Programming .  All these objects are stored on separate memory called Heap.  Heap is memory which allocated during runtime.

GARBAGE COLLECTION IN PYTHON:- Python’s memory allocation and de-allocation method is automatic. Python uses two strategies for memory allocation:  Reference counting  Garbage collection  the Python interpreter only used reference counting for memory management. Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero, the object is de-allocated.

about python

 Python is simple to use, but it is a real programming language, offering much more structure and support for large programs than shell scri...