pap ass 3
Q1 Explain __init__ & __str__ method with an example
Ans : __init__ method
__init__ is a special method in Python classes, it is the constructor method for a class. In the following example you can see how to use it.
class Student(object):
"""
Returns a ```Student``` object with the given name, branch and year.
"""
def __init__(self, name, branch, year):
self.name = name
self.branch = branch
self.year = year
print("A student object is created.")
def print_details(self):
"""
Prints the details of the student.
"""
print("Name:", self.name)
print("Branch:", self.branch)
print("Year:", self.year)
example
class time()
h=0
m=0
s=0
def __init__(self>h,m,s):
self.h=h
self.m=m
self.s=s
def display(t):
print(‘%2,d:%2d:%2d’%(t.h,t.m,t.s))
t1=time(11,58,20)
time.display(t1)
output 11:58:20
__str__ method
Str is special method that returns the string represents of an object
Self Is an argument that must be passed to the __str__ method
Class student( ):
Def __init__(self,name,marks):
Self.name=name
Self.marks=marks
Def __str__(self):
Returns ‘(%s,%2d)’ % (self.name,self.marks)
St= student (“AAA”,95)
Print(st)
Output (AAA,95)
Q2 Explain operator overloading
Ans # Python program to overload equality
# and less than operators
class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is lessthan ob2"
else:
return "ob2 is less than ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)
ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)
Output :
ob1 is lessthan ob2
Not equal
Q3 Explain polymorphism
Ans Polymorphism
Sometimes an object comes in many types or forms. If we have a button, there are many different draw outputs (round button, check button, square button, button with image) but they do share the same logic: onClick(). We access them using the same method . This idea is called Polymorphism.
Polymorphism is based on the greek words Poly (many) and morphism (forms). We will create a structure that can take or use many forms of objects.
class Bear(object): def sound(self): print("Groarrr") class Dog(object): def sound(self): print("Woof woof!") def makeSound(animalType): animalType.sound() bearObj = Bear()dogObj = Dog() makeSound(bearObj)makeSound(dogObj)
output
GroarrrWoof woof!
Q4 Explain socket with an example
Ans
Sockets are used in networking. The idea of a socket is to aid in the communication between two entities. When you view a website, you are opening a port and connecting to that website via sockets.
import socket
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()
server = "pythonprogramming.net"
port = 443
server_ip = socket.gethostbyname(server)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = context.wrap_socket(s, server_hostname=server)
request = "GET / HTTP/1.1\nHost: "+server+"\n\n"
s.connect((server,port))
s.send(request.encode())
result = s.recv(4096)
while (len(result) > 0):
print(result)
result = s.recv(4096)
Ans : __init__ method
__init__ is a special method in Python classes, it is the constructor method for a class. In the following example you can see how to use it.
class Student(object):
"""
Returns a ```Student``` object with the given name, branch and year.
"""
def __init__(self, name, branch, year):
self.name = name
self.branch = branch
self.year = year
print("A student object is created.")
def print_details(self):
"""
Prints the details of the student.
"""
print("Name:", self.name)
print("Branch:", self.branch)
print("Year:", self.year)
example
class time()
h=0
m=0
s=0
def __init__(self>h,m,s):
self.h=h
self.m=m
self.s=s
def display(t):
print(‘%2,d:%2d:%2d’%(t.h,t.m,t.s))
t1=time(11,58,20)
time.display(t1)
output 11:58:20
__str__ method
Str is special method that returns the string represents of an object
Self Is an argument that must be passed to the __str__ method
Class student( ):
Def __init__(self,name,marks):
Self.name=name
Self.marks=marks
Def __str__(self):
Returns ‘(%s,%2d)’ % (self.name,self.marks)
St= student (“AAA”,95)
Print(st)
Output (AAA,95)
Q2 Explain operator overloading
Ans # Python program to overload equality
# and less than operators
class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is lessthan ob2"
else:
return "ob2 is less than ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)
ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)
Output :
ob1 is lessthan ob2
Not equal
Q3 Explain polymorphism
Ans Polymorphism
Sometimes an object comes in many types or forms. If we have a button, there are many different draw outputs (round button, check button, square button, button with image) but they do share the same logic: onClick(). We access them using the same method . This idea is called Polymorphism.
Polymorphism is based on the greek words Poly (many) and morphism (forms). We will create a structure that can take or use many forms of objects.
class Bear(object): def sound(self): print("Groarrr") class Dog(object): def sound(self): print("Woof woof!") def makeSound(animalType): animalType.sound() bearObj = Bear()dogObj = Dog() makeSound(bearObj)makeSound(dogObj)
output
GroarrrWoof woof!
Q4 Explain socket with an example
Ans
Sockets are used in networking. The idea of a socket is to aid in the communication between two entities. When you view a website, you are opening a port and connecting to that website via sockets.
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()
server = "pythonprogramming.net"
port = 443
server_ip = socket.gethostbyname(server)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = context.wrap_socket(s, server_hostname=server)
request = "GET / HTTP/1.1\nHost: "+server+"\n\n"
s.connect((server,port))
s.send(request.encode())
result = s.recv(4096)
while (len(result) > 0):
print(result)
result = s.recv(4096)
Q5
Explain xml with an example
Ans XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language.
What is XML?
The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.
XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone.
#Import required library
import xml.etree.ElementTree as xml
def createXML(filename):
# Start with the root element
root = xml.Element("users")
children1 = xml.Element("user")
root.append(children1)
tree = xml.ElementTree(root)
with open(filename, "wb") as fh:
tree.write(fh)
if __name__ == "__main__":
createXML("testXML.xml")
Q6Explain json
Ans JSON in Python
Python has a built-in package called json, which can be used to work with JSON data.
import json
# some
JSON:x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:y = json.loads(x)# the result is a Python dictionary:print(y["age"])
Convert from Python to JSON:
import json# a Python object
(dict):
x = { "name": "John", "age": 30, "city": "New York"}
# convert into JSON:
y = json.dumps# the result is a JSON string:
print(y)