Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Object – Oriented Programming in Python-1-1

Uploaded by

rukkuddha1818
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Object – Oriented Programming in Python-1-1

Uploaded by

rukkuddha1818
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Working with : API

• What is API ?
• What is Web API?
• Advantages of using a Web API.
• Requests Library(requests library).
• Git and GitHub Repositories.
What is API?
• API – (Application Programming interface)
• API is a set of protocols , routines, and tools for building software and applications.
• It specifies how software components should interact and API’s allow
communication b/w different systems or platforms.
• API acts as an intermediary between two systems.

What is Web API?


• It’s a type of API that is hosted on the web and accessed over the internet using
standard web protocols such as HTTP
• A Web API is used to allow communication b/w a web application and a server.
• It is designed to provide an interface for web applications to interact with a server,
to making it possible for web application to access resources and data from a server
and vice versa.
• EX: Private weather applications, they can use a weather API to access and retrieve
weather data from a source such as a government weather agency.
Advantages of Web API:
• Easy Access
• Flexibility
• Cost-Effective
• Scalability
• Interoperability
• Reusability

API Key:
• API Key acts as a secret code that identifies the calling program and grants access
to the API’s data and functionality.
• The use of API key helps to ensure that the API is used only by authorized clients
and helps to maintain the security and integrity of the data and services provided
by the API.
Requests Library(requests):
• It is a python library used to send http requests.
• It is designed to provide a simple and intuitive interface for making http requests.
• The basic use of requests involves sending an http requests to specified URL , and
processing the response that is received from the server.
• This process can be done by using requests. get method for making GET requests,
or the requests.post method for making POST requests.
• commands to install requests library pip install requests.
• Ex: https://api.genderize.io offers an API that determines the gender, to utilize the
API, the name is passed as a parameter in the url.
URL : https://api.genderize.io/?name=Chandhana
URL : https://api.apilayer.com/fixer/convert?
to={to_currency}&from={from_currency}&amount={amount}&apikey={api_ke
y}
• The API then returns the results in JSON format, including information such as the
name, gender and a probability score.
• An example of the API’s response, When the name “Chandhana ” is passed.
• Response : {"count":26,"name":"chandhana","gender":"female","probability":0.54}
This program uses web API to find the gender based on name.

import requests

str = input(“Enter your name(I will tell your gender):”)


url = “ https://api.genderize.io/?name =”+str
response = requests. get(url)

if response .status_code = = 200: Output:


data = response.json() Enter your name(I will tell your gender):
Chandhana
print(“Name:”, data[‘name’]) Name: Chandhana
print(“Gender:”, data[‘gender’]) Gender: female
else:
print(“Failed to retrieve data”)
Git and GitHub Repositories:
• It is a version control systems and hosting platforms for software
development, They store and manage large amounts of codes,
documentation, and other files related to software projects.
• Git : It helps manage and keep track of changes made to a project’s
codebase.
• It allows developers to store different versions of the codebase and revert
back to an earlier version if needed.
• Git also enables multiple developers to collaborate on the same codebase,
making it easier to merge their changes without conflicts.
• GitHub: It is a web-based platform that hosts Git repositories.
• It is used to manage and store Git repositories and provides additional
features like bug tracking, project management, and collaboration tools.
• Developers can use GitHub to contribute to open-source projects, share
their own projects with others, and use Git to keep track of changes to the
code.
• GitHub also provides a GUI to interact with the Git repositories and visualizes the
activity and changes in a project’s codebase.
• The repositories in Git and GitHub contain real-world data, including source code,
multimedia files, and other related resources, which are managed and maintained
by a global community of developers and open-source enthusiasts.
• Both are essential tools for developers, offerings a vast and constantly growing
collections of real-world data for those looking to expand their knowledge and
advance their careers.
Object – Oriented Programming
in Python
• Introduction
• Features of OOP
• Classes and Objects
• Constructor Methods
• Attributes and Variables
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
Object Oriented Programming (oop):
• Oop is a programming paradigm in which concepts are represented as objects that
have data fields(data members) and associated functions(member functions).
• Object communicate which each other by exchanging messages.
• The program is divided into number of small units called object. The data and
function are built around these object.
• The functions of one object can access the functions of other object.
Basic Concepts of Object Oriented Programming(Features):
1. Class : A blueprint for creating objects. It contains attributes (data) and methods
(functions).
2. Object: An instance of a class that contains the actual data.
3. Encapsulation: It combines data and functions inside a class. Hides the data from
being accessed from a class directly, only through the functions inside the class is
able to access the information.
4. Abstraction: To reduce the complexity by hiding implementation details and
exposing only relevant information to the user.
5. Inheritance: The ability of a new class to inherit the properties and behaviors
from an existing class.
6. Polymorphism: Polymorphism is the ability to exist in more than one form. An
operation may exhibit different behavior in different instances. Behavior depends
on the type of data used in the operation.
Classes :
• It is a blueprint or template for creating objects.
• It defines a set of attributes and methods that represent the characteristics and
behavior of an objects created from the class.
• Class is a also collections of objects.
• Class = Data Members + Member Functions, Ex: Class (customer), 3 customers
(object) with data and methods.
Defining classes in Python:
• In python , a class is defined using the class keyword, followed by the class name
and a colon.
• Class body contains class variables, constructor methods, class level method and
instance methods.
• The class body is indented. The indentation of the code within the class body, it
indicates the start and end of the class definition.
• A class can be empty : class EmptyClass:
pass
• A class is defined without any members, above example defines an empty class
using the pass keyword.
• The pass statement is used to indicate that the body of the class is intentionally left
empty.
• Constructor is a special method that is automatically called when an object is
created, purpose calling is to assign values to the data members of the class to
establish the core functions of the object.
• The name of the constructor method is always: __init__
Above program is an Ex: of
Parameterized Constructor
Creating Multiple Objects:
How Objects are Stored in Memory?
Example:
class Person:
def init(self, name, age):
self.name=name
self.age = age
#create two objects for a class Person
person1 = Person(“Srikanth”, 30)
person2= Person(“Srinath”,25)
person3= Person2 #person3 is assigned to the same object as person2.
#Both,person2 and person3 refer same object in memory.
• Person1,2,3 are reference variables are stored in memory region called as STACK
memory.
• When object is no longer needed, the python interpreter will automatically release
the memory associated with that object, a process called as “Garbage Collection”.
What is Garbage Collection?
• It is an automatic memory management used by programming language
and runtime environment.
• It free up memory that is no longer needed by the program, by detecting and
removing objects that are no longer being referenced.
• It helps to avoid memory leaks and reduce memory related errors in the
program.
• Goal: to manage memory and reduce the risk of bugs.

How Garbage collection is handled by python?


• It handles by the python interpreter using combination of reference counting
and cycle detection algorithm.
• Reference Counting: it maintains a count of references to each object in
memory, when reference count is zero, then object is no longer required and
can be collected as garbage.(not in case of circular references?).
• Cycle Detection Algorithm: Which identifies objects that are involved in
circular references and frees the memory associated with them.
Working of Constructor :
• Types of Constructor in Python
• There are three types of constructors in Python or other programming
1.Default constructor 2.Non-parameterized & 3.Parameterized constructor
Default Constructor:
# Class creation.
class Employee:
emp_name = "John"
emp_id = 12345
# Declare a function that accepts an argument self.
def display(self):
print("Name: ", self.emp_name)
print("Id: ", self.emp_id)
# Outside the class definition.
# Create an object of the class Employee.
emp = Employee()
# Call the function.
emp.display()
Output: Name:
John Id: 12345
Encapsulation: It bundles the data and behavior of an object within a single unit.
Goal : It is to secure data from any unauthorized modifications from outside sources.
class BankAccount:
def _init_(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount

#creating an instance of the BankAccount class


bank_account = BankAccount(1000)
#Accessing the balance directly and modifying it
print(“Old balance:”,bank_account.balance)
bank_account.balance -= 100
print(“New balance:”, bank_account.balance)
Benefits of Encapsulation:
• Protection of objects from unauthorized access.
• Prevention of access to private class members by other classes
• Avoid modifying data through private and protected access levels.
• Increased security by protecting code and logic from external inheritance.

Access Modifiers: It is used to limit the access to the variable and methods of a class.
python provides three types of access modifiers such as public, private and protected.

Public : By default, all attributes and methods are public and can be accessed from
anywhere in the code.

Private : To make an attribute or method private in python, prefix its name with two
underscore (__). Private properties can only be accessed within the same class and not
accessible from outside the class.
Protected : we use single underscore (_). Protected properties can’t be accessed from
outside the class, but can still be accessed within subclasses.
class Person:
def _int_(self, name, age, sal):
self.name = name #public member, can be accessed from outside the class.
self._age = age #protected member, used within the class and its subclasses.
self.__salary = sal # private member, accessed within the same class.

def display_details(self):
print(“Name:”, self.name)
print(“Age:”, self._age)
print(“Salary:”, self.__salary)

person = Person(“Praveen”, 25, 20000)


person.display_details()
Output: Name : Praveen
Age: 25
Salary: 20000

You might also like