Get Instant Help From 5000+ Experts For
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing:Proofread your work by experts and improve grade at Lowest cost

And Improve Your Grades
myassignmenthelp.com
loader
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Guaranteed Higher Grade!
Free Quote
wave

What is the main point of OOP in Python?

1. What is the main point of OOP in Python?

Python is basically an object oriented programming language. In OOP the objects are given more importance than the manipulation on them.  The four main principles of object orientation are:

Data Abstraction- It models the classes with respect to the problem simplifying the complex reality.

Encapsulation- It involves the process of hiding the details from the other objects

Inheritance - It is a process of deriving the new class from the existing class

Polymorphism- It is the process of using the operator and function with different parameter inputs.

A python class for Student is created as follows:

class Student:

stuCount = 0

def __init__(self, name, marks):

self.name = name

self. marks = marks

Student.stuCount += 1

def displayCount(self):

print "Total Student %d" % Student.stuCount

def displayStudent (self):

print "Name : ", self.name,  ", Marks: ", self. marks 

2. Where does an inheritance search look for an attribute?

The inheritance search look for an attribute first in the derived class and then in its base class and the search goes up until it finds the object or reach the top base class.

3. What is multiple inheritance?

Multiple inheritance involves deriving a new class from more than one base class. For example consider two base class Base1 and Base2 and newly derived class Derived that is derived from both Base1 and Base2.

Multiple inheritance is done in python in the following ways:

class Base1:

pass

class Base2:

pass

class Derived(Base1, Base2):

pass

 4. What is the difference between a class object and an instance object?

Class Object is copy of the class whereas the instance object reference the class object.

Class objects are contains the memory for variables of the class while the instance object contains only the memory address of the Class object.

5. What is the __init__ method used for?

__init__ is a constructor method which is used to initialize class instance or object. The un-parameterized function init also takes self as a parameter.  The self-variable represents the instance of the object.

Example:

def __init__(self, name, marks):

self.name = name

self. marks = marks

6. How do you create a class instance?

We can create a class instance by calling the class directly. Parameters passed in the object instance creation are sent to __init__ function.

Example:

stu2 = Student("John",123)

stu2.displayStudent()

7. How do you create a class?

The class are created in python using the class statement. The class name is specified after the class keyword. The class name is then followed by the colon. A sample Student class is created as follows.

Example:

class Student:

stuCount = 0

def __init__(self, name, marks):

self.name = name

self. marks = marks

Student.stuCount += 1

def displayCount(self):

print "Total Student %d" % Student.stuCount

def displayStudent (self):

print "Name : ", self.name,  ", Marks: ", self. marks

 8. What is a superclass and how do you specify a class’s superclasses?

Super class are the base class from which the child class/ sub classes are derived. All the properties of the super class can now be used by the sub class. The superclass of the class is passed as argument to the child class as shown below:

Where does an inheritance search look for an attribute?

Class SubClassName(SuperClassName):

9. Give an example of classes and use of them from QT or SQLITE 3.

An example program to create table in SQLITE3 in python and add rows to the created table.

Example:

import sqlite3
connection = sqlite3.connect('sample')
cur = connection.cursor()
cur.execute("""drop table if exists student""")
connection.commit()
cur.execute("""create table Student (
sid     int     primary key not NULL ,
name    text, marks          int)""")
cur.execute("""insert into Student values (1, "John", 84)""")
cur.execute("""insert into Student values (2, "Mary",92)""")
connection.commit()
cur.execute ("""select * from Student""")
for row in cur:
print (row)
c.close()

10. Name three things that exception processing is good for.

Exception processing reduces the error-checking code the program requires. When error occurs the exception processing changes the flow of control of the program and recovers from the error. Thus exception processing is useful for handling the errors that occurs at run time and for notifying the errors that occur during program execution without disturbing the execution of the program.

11. What happens to an exception if you don’t do anything special to handle it?

Python is provided with a default exception handler, all uncaught exception are filtered up by the default exception handler which is at the top of the program. The handler prints the error message and terminate the program execution.

Example:

a=10

b=0

num=a/b

print(num)

Output:

12. How can your script recover from an exception?

The python script can recover from exception with the help of exception handling mechanism using try/except statement. A handling on the exception is done to recover from failure and to continue with other operation. For example consider the program below which reads the files in the current directory and returns the statement containing content keyword.

Example:

def divide(a,b):

try:

result = a/b

except ZeroDivisionError:

print ("Dividion by zero is not possible")

else:

print ("Quotient is", result)

ans=divide(10,0)

ans=divide(10,5)

Output:

13. What is the try statement for?

 In Python try statement is used for handling exceptions in the program that occurs at the run time. The try statement is used to catch the exception and recover from them. When exception occurs the current process gets stopped and the control passes to the calling process until it is handled. An example program for the try statement is

import sys

randElements = ['a', 0, 2]

for element in randElements:

try:

print("The element is", element)

reciprocal = 1/int(element)

break

except:

print("Sorry ",sys.exc_info()[0],"occurs.")

print()

print("The reciprocal of ", element," is ", reciprocal)

Output:

14. What are the two common variations of the try statement?

The two common variations in the try statement are try-except-else and try-finally

In try-except-else, the program statements prone to raise exception are placed in the try block. The try block is followed by except statement which handles the error elegantly. At-last the except statement is followed by the else statement. The program statements in the else block is executed when no exception occurs in execution of the program.

Example:

try:

fh = open("file", "r")

fh.write("Test for exception handling!!")

except IOError:

print ("Exception: can't find file")

else:

print ("Data contents are written in the file successfully")

Output:

In try-finally, the statement in finally block is executed whether or not exception occurs in the try bock.

Example:

try:

fh = open("file", "w")

try:

fh.write("Test for exception handling!!")

finally:

print ("Closing the file")

fh.close()

except IOError:

print ("Exception: can't find file")

Output:

15. What is the raise statement for?

Raise statement is used for manually raising the exception. The raise statement is expressed as follows:

raise [Exception [, args [, traceback]]]

Where Exception determines the type of exception,

args – Exception arguments

Example:

try:

raise ValueError ("Raising Exception using raise statement")

except ValueError as arg:

print (arg.args)

Output:

16. What is the assert statement designed to do, and what other statement is it like?

Assert statement is used to evaluate the expression, if the expression return false it sends the AssertionError exception.

Example:

def KToF(temp):

assert (temp >= 0),"Absolute zero colder"

return ((temp-273)*1.8)+32

print (KToF(260))

print (int(KToF(423.78)))

print (KToF(-5))

Output:

17. What is the with/as statement designed to do, and what other statement is it like?

With statement:

With statement is used to simplify the exception handling by encapsulating the preparation and memory clean up. With statement is used for handling exception more effectively. With statement is automatically calls the clean-up function and ensures memory clean-up is done.

Consider the following program for opening the file and reading its content using with statement:

For example:

with open("file.txt") as fileHandle:

dataTxt = fileHandle.read()

print (dataTxt)

Here the close() is not called. It is implicitly called by with statement.

Without with statement the file operation is performed as follows:

fileHandle = open("file.txt")

dataTxt = fileHandle.read()

print (dataTxt)

fileHandle.close() 

Here the close () is explicitly called.

Output:

18. Write a function named readposint that uses the input dialog to prompt the user for a positive integer and then checks the input to confirm that it meets the requirements. It should be able to handle inputs that cannot be converted to int, as well as negative ints, and edge cases (e.g. when the user closes the dialog, or does not enter anything at all.).

from tkinter import *

from tkinter import messagebox

def inp():

global inputValue

num=inputValue.get()

try:

if(int(num) < 0):

raise ValueError

info.configure(text=num)

except ValueError:

info.configure(text="Please enter only positive integers")

root.update()

def on_closing():

if messagebox.askokcancel("Quit", "Do you want to close?"):

root.destroy()

root=Tk()

root.protocol("WM_DELETE_WINDOW", on_closing)

root.geometry("500x100")

Label(root,text="Please enter the input value: ", height=1, width=30).grid(row=0)

inputValue=Entry(root, width=35)

inputValue.grid(row=0, column=1)

info=Label(root,text="", height=1)

info.grid(row=5, column=1)

get=Button(root, text="Input", command=inp)

get.grid(row=3, column=1)

mainloop()

Output:

Cite This Work

To export a reference to this article please select a referencing stye below:

My Assignment Help. (2022). Essay: OOP In Python - Principles, Inheritance, And Exception Handling.. Retrieved from https://myassignmenthelp.com/free-samples/fit9133-programming-foundations-in-python/principles-of-object-orientation-file-A8BC38.html.

"Essay: OOP In Python - Principles, Inheritance, And Exception Handling.." My Assignment Help, 2022, https://myassignmenthelp.com/free-samples/fit9133-programming-foundations-in-python/principles-of-object-orientation-file-A8BC38.html.

My Assignment Help (2022) Essay: OOP In Python - Principles, Inheritance, And Exception Handling. [Online]. Available from: https://myassignmenthelp.com/free-samples/fit9133-programming-foundations-in-python/principles-of-object-orientation-file-A8BC38.html
[Accessed 26 April 2024].

My Assignment Help. 'Essay: OOP In Python - Principles, Inheritance, And Exception Handling.' (My Assignment Help, 2022) <https://myassignmenthelp.com/free-samples/fit9133-programming-foundations-in-python/principles-of-object-orientation-file-A8BC38.html> accessed 26 April 2024.

My Assignment Help. Essay: OOP In Python - Principles, Inheritance, And Exception Handling. [Internet]. My Assignment Help. 2022 [cited 26 April 2024]. Available from: https://myassignmenthelp.com/free-samples/fit9133-programming-foundations-in-python/principles-of-object-orientation-file-A8BC38.html.

Get instant help from 5000+ experts for
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing: Proofread your work by experts and improve grade at Lowest cost

loader
250 words
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Plagiarism checker
Verify originality of an essay
essay
Generate unique essays in a jiffy
Plagiarism checker
Cite sources with ease
support
Whatsapp
callback
sales
sales chat
Whatsapp
callback
sales chat
close