Unit 4 Cse

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

[Unit 4]

Python File Handling exists with the same name. The file
pointer exists at the beginning of the
Till now, we were taking the input from the console and
file.
writing it back to the console to interact with the user.
The file handling plays an important role when the data
6 wb It opens the file to write only in
needs to be stored permanently into the file. A file is a
binary format. It overwrites the file if
named location on disk to store related information. We can
it exists previously or creates a new
access the stored information (non-volatile) after the
one if no file exists. The file pointer
program termination.
exists at the beginning of the file.
The file-handling implementation is slightly lengthy or
complicated in the other programming language, but it is
7 w+ It opens the file to write and read
easier and shorter in Python.
both. It is different from r+ in the
In Python, files are treated in two modes as text or binary.
sense that it overwrites the previous
The file may be in the text or binary format, and each line of
file if one exists whereas r+ doesn't
a file is ended with the special character.
overwrite the previously written file.
Hence, a file operation can be done in the following order.
It creates a new file if no file exists.
o Open a file
The file pointer exists at the
o Read or write - Performing operation
beginning of the file.
o Close the file

Opening a file 8 wb+ It opens the file to write and read


Python provides an open() function that accepts two both in binary format. The file
arguments, file name and access mode in which the file is pointer exists at the beginning of the
accessed. The function returns a file object which can be file.
used to perform various operations like reading, writing, etc.
Syntax: 9 a It opens the file in the append mode.
1. file object = open(<file-name>, <access- The file pointer exists at the end of
mode>, <buffering>) the previously written file if exists
The files can be accessed using various modes like read, any. It creates a new file if no file
write, or append. The following are the details about the exists with the same name.
access mode to open a file.
1 ab It opens the file in the append mode
SN Access Description 0 in binary format. The pointer exists
mode at the end of the previously written
file. It creates a new file in binary
format if no file exists with the same
1 r It opens the file to read-only mode. name.
The file pointer exists at the
beginning. The file is by default 1 a+ It opens a file to append and read
open in this mode if no access mode 1 both. The file pointer remains at the
is passed. end of the file if a file exists. It
creates a new file if no file exists
2 rb It opens the file to read-only in with the same name.
binary format. The file pointer exists
at the beginning of the file. 1 ab+ It opens a file to append and read
2 both in binary format. The file
3 r+ It opens the file to read and write pointer remains at the end of the file.
both. The file pointer exists at the
beginning of the file.

4 rb+ It opens the file to read and write Example


both in binary format. The file 1. #opens the file file.txt in read mode
pointer exists at the beginning of the 2. fileptr = open("file.txt","r")
file. 3. if fileptr:
4. print("file is opened successfully")
5 w It opens the file to write only. It Output:
overwrites the file if previously <class '_io.TextIOWrapper'>
exists or creates a new one if no file file is opened successfully

[By.- Prof. Narendra Kumar_CSE] Page 1


[Unit 4]
In the above code, we have passed filename as a first Snapshot of the file2.txt
argument and opened file in read mode as we mentioned r as
the second argument. The fileptr holds the file object and if
the file is opened successfully, it will execute the print
statement
The close () method
Once all the operations are done on the file, we must close it
through our Python script using the close() method. Any We have opened the file in w mode. The file1.txt file doesn't
unwritten information gets destroyed once exist, it created a new file and we have written the content in
the close() method is called on a file object. the file using the write() function.
We can perform any operation on the file externally using
the file system which is the currently opened in Python;
hence it is good practice to close the file once all the
The file related methods
operations are done.
The syntax to use the close() method is given below. The file object provides the following methods to
Syntax manipulate the files on various operating systems.
1. fileobject.close()
Consider the following example. SN Method Description
1. # opens the file file.txt in read mode
2. fileptr = open("file.txt","r") 1 file.close() It closes the opened
3. if fileptr: file. The file once
4. print("file is opened successfully") closed, it can't be
5. #closes the opened file read or write
6. fileptr.close() anymore.
After closing the file, we cannot perform any operation in
the file. The file needs to be properly closed. If any 2 File.fush() It flushes the internal
exception occurs while performing some operations in the buffer.
file then the program terminates without closing the file.
We should use the following method to overcome such type 3 File.fileno() It returns the file
of problem. descriptor used by
1. try: the underlying
2. fileptr = open("file.txt") implementation to
3. # perform file operations request I/O from the
4. finally: OS.
5. fileptr.close()
4 File.isatty() It returns true if the
Writing the file file is connected to a
To write some text to a file, we need to open the file using TTY device,
the open method with one of the following access modes. otherwise returns
w: It will overwrite the file if any file exists. The file pointer false.
is at the beginning of the file.
a: It will append the existing file. The file pointer is at the 5 File.next() It returns the next
end of the file. It creates a new file if no file exists. line from the file.
Example
1. # open the file.txt in append mode. Create a new file if no su 6 File.read([size]) It reads the file for
ch file exists. the specified size.
2. fileptr = open("file2.txt", "w")
3. # appending the content to the file 7 File.readline([size]) It reads one line
4. fileptr.write('''''Python is the modern day language. It makes from the file and
things so simple. places the file
5. It is the fastest-growing programing language''') pointer to the
6. # closing the opened the file beginning of the new
7. fileptr.close() line.
Output:
File2.txt 8 File.readlines([sizehint] It returns a list
Python is the modern-day language. It makes things so ) containing all the
simple. It is the fastest growing programming language.

[By.- Prof. Narendra Kumar_CSE] Page 2


[Unit 4]

lines of the file. It Loading the module in our


reads the file until
the EOF occurs python code
using readline() We need to load the module in our python code to
function. use its functionality. Python provides two types of
statements as defined below.
9 File.seek(offset[,from) It modifies the
position of the file 1. The import statement
pointer to a specified 2. The from-import statement
offset with the
specified reference.
The import statement
1 File.tell() It returns the current
The import statement is used to import all the
0 position of the file
pointer within the functionality of one module into another. Here, we
file. must notice that we can use the functionality of any
python source file by importing that file as the
1 File.truncate([size]) It truncates the file to module into another python source file.
1 the optional We can import multiple modules with a single
specified size. import statement, but a module is loaded once
regardless of the number of times, it has been
1 File.write(str) It writes the
2 specified string to a
imported into our file.
file The syntax to use the import statement is given
below.
1 File.writelines(seq) It writes a sequence 1. import module1,module2,........ module n
3 of the strings to a Hence, if we need to call the function displayMsg()
file. defined in the file file.py, we have to import that file
as a module into our module as shown in the
Python Modules example below.
A python module can be defined as a python Example:
program file which contains a python code including 1. import file;
python functions, class, or variables. In other words, 2. name = input("Enter the name?")
we can say that our python code file saved with the 3. file.displayMsg(name)
extension (.py) is treated as the module. We may
have a runnable code inside the python module. Output:
A module in Python provides us the flexibility to Enter the name?John
organize the code in a logical way. Hi John

Example The from-import statement


We will create a module named as file.py which contains Instead of importing the whole module into the
a function func that contains a code to print some namespace, python provides the flexibility to import only
message on the console. the specific attributes of a module. This can be done by
Let's create the module named as file.py. using from? import statement. The syntax to use the
1. #displayMsg prints a message to the name being passed. from-import statement is given below.
1. from < module
2. def displayMsg(name) name> import <name 1>, <name 2>..,<name n>
3. print("Hi "+name); Consider the following module named as calculation
which contains three functions as summation,
multiplication, and divide.
calculation.py:
1. #place the code in the calculation.py
2. def summation(a,b):
3. return a+b

[By.- Prof. Narendra Kumar_CSE] Page 3


[Unit 4]
4. def multiplication(a,b): python source file. Let's create a simple python
5. return a*b; source file at our home directory (/home) which uses
6. def divide(a,b): the modules defined in this package.
7. return a/b;
Main.py:
Test.py
1. from calculation import summation 1. import Employees
2. #it will import only the summation() from calculation.py 2. print(Employees.getNames())
Output:
3. a = int(input("Enter the first number")) ['John', 'David', 'Nick', 'Martin']
4. b = int(input("Enter the second number")) We can have sub-packages inside the packages. We
5. print("Sum = ",summation(a,b)) #we do not need to spec can nest the packages up to any level depending
ify the module name while accessing summation()
Output:
upon the application requirements.
Enter the first number10 The following image shows the directory structure of
Enter the second number20 an application Library management system which
Sum = 30 contains three sub-packages as Admin, Librarian,
and Student. The sub-packages contain the python
Python packages modules.
The packages in python facilitate the developer with
the application development environment by
providing a hierarchical directory structure where a
package contains sub-packages, modules, and sub-
modules. The packages are used to categorize the
application level code efficiently.
Let's create a package named Employees in your
home directory. Consider the following steps.
1. Create a directory with name Employees on path
/home.
2. Create a python source file with name
ITEmployees.py on the path /home/Employees.
ITEmployees.py
1. def getITNames():
2. List = ["John", "David", "Nick", "Martin"] Python Program for Sieve of
3. return List;
3. Similarly, create one more python file with name
Eratosthenes
Problem statement − we are given a number n, we need
BPOEmployees.py and create a function
to print all primes smaller than or equal to n. Constraint: n
getBPONames(). is a small number.
4. Now, the directory Employees which we have
created in the first step contains two python modules. Example
To make this directory a package, we need to include
one more file here, that is __init__.py which contains def SieveOfEratosthenes(n):
the import statements of the modules defined in this
# array of type boolean with True values in it
directory.
__init__.py prime = [True for i in range(n + 1)]
1. from ITEmployees import getITNames
2. from BPOEmployees import getBPONames p=2
5. Now, the directory Employees has become the
package containing two python modules. Here we while (p * p <= n):
must notice that we must have to create __init__.py
inside a directory to convert this directory to a # If it remain unchanged it is prime
package. if (prime[p] == True):
6. To use the modules defined inside the package
Employees, we must have to import this in our # updating all the multiples

[By.- Prof. Narendra Kumar_CSE] Page 4


[Unit 4]
Python has many built-in exceptions that enable our
for i in range(p * 2, n + 1, p):
program to run without interruption and give the output.
These exceptions are given below:
prime[i] = False

p += 1
Common Exceptions
prime[0]= False Python provides the number of built-in exceptions, but here
we are describing the common standard exceptions. A list of
prime[1]= False common exceptions that can be thrown from a standard
Python program is given below.
# Print 1. ZeroDivisionError: Occurs when a number is
divided by zero.
for p in range(n + 1): 2. NameError: It occurs when a name is not found. It
may be local or global.
if prime[p]: 3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation
print (p,end=" ") fails.
5. EOFError: It occurs when the end of the file is
# main reached, and yet operations are being performed.

if __name__=='__main__':

n = 33
Exception handling in python
print ("The prime numbers smaller than or equal to", The try-expect statement
n,"is") If the Python program contains suspicious code that may
throw the exception, we must place that code in
SieveOfEratosthenes(n) the try block. The try block must be followed with
Output the except statement, which contains a block of code that
will be executed if there is some exception in the try block.
The prime numbers smaller than or equal to 33 is
2 3 5 7 11 13 17 19 23 29 31

Python Exception
An exception can be defined as an unusual condition in a
Syntax
program resulting in the interruption in the flow of the
1. try:
program.
2. #block of code
Whenever an exception occurs, the program stops the
3. except Exception1:
execution, and thus the further code is not executed.
4. #block of code
Therefore, an exception is the run-time errors that are unable
5. except Exception2:
to handle to Python script. An exception is a Python object
6. #block of code
that represents an error.
7. #other code
Python provides a way to handle the exception so that the
8. Consider the following example.
code can be executed without any interruption. If we do not
9. Example 1
handle the exception, the interpreter doesn't execute all the
10. try:
code that exists after the exception.
11. a = int(input("Enter a:"))
12. b = int(input("Enter b:"))
13. c = a/b

[By.- Prof. Narendra Kumar_CSE] Page 5


[Unit 4]
14. except: The easiest way to think of an assertion is to liken it
15. print("Can't divide with zero") to a raise-if statement (or to be more accurate, a
16. Output: raise-if-not statement). An expression is tested, and
Enter a:10
Enter b:0 if the result comes up false, an exception is raised.
Can't divide with zero
The assert Statement
We can also use the else statement with the try-except
statement in which, we can place the code which will be When it encounters an assert statement, Python
executed in the scenario if no exception occurs in the try evaluates the accompanying expression, which is
block. hopefully true. If the expression is false, Python
raises an AssertionError exception.
The except statement with no exception The syntax for assert is −
assert Expression[, Arguments]
Python provides the flexibility not to specify the name of
exception with the exception statement. If the assertion fails, Python uses
ArgumentExpression as the argument for the
Example AssertionError. AssertionError exceptions can be
1. try: caught and handled like any other exception using
2. a = int(input("Enter a:")) the try-except statement, but if not handled, they
3. b = int(input("Enter b:")) will terminate the program and produce a traceback.
4. c = a/b;
5. print("a/b = %d"%c)
6. except: Example
7. print("can't divide by zero")
Here is a function that converts a temperature from
8. else:
9. print("Hi I am else block") degrees Kelvin to degrees Fahrenheit. Since zero
degrees Kelvin is as cold as it gets, the function
bails out if it sees a negative temperature −
The except statement using with exception #!/usr/bin/python
variable
We can use the exception variable with def KelvinToFahrenheit(Temperature):
the except statement. It is used by using the as keyword. this assert (Temperature >= 0),"Colder than absolute
object will return the cause of the exception. Consider the zero!"
following example:
1. try:
return ((Temperature-273)*1.8)+32
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:")) print KelvinToFahrenheit(273)
4. c = a/b print int(KelvinToFahrenheit(505.78))
5. print("a/b = %d"%c) print KelvinToFahrenheit(-5)
6. # Using exception object with the except statement
7. except Exception as e: result −
8. print("can't divide by zero") 32.0
9. print(e) 451
10. else: Traceback (most recent call last):
11. print("Hi I am else block") File "test.py", line 9, in <module>
Output: print KelvinToFahrenheit(-5)
Enter a:10 File "test.py", line 4, in KelvinToFahrenheit
Enter b:0
can't divide by zero
assert (Temperature >= 0),"Colder than absolute
division by zero zero!"
AssertionError: Colder than absolute zero!

Assertions in Python
An assertion is a sanity-check that you can turn on or
turn off when you are done with your testing of the
program.
[By.- Prof. Narendra Kumar_CSE] Page 6
[Unit 4]

Instance − An individual object of a certain


Python OOPs Concepts 
class. An object obj that belongs to a class
Circle, for example, is an instance of the
Python is also an object-oriented language since its class Circle.
beginning. It allows us to develop applications using an
Object-Oriented approach. In Python, we can easily create  Instantiation − The creation of an instance
and use classes and objects. of a class.

An object-oriented paradigm is to design the program using


 Method − A special kind of function that is
classes and objects. The object is related to real-word defined in a class definition.
entities such as book, house, pencil, etc. The oops concept  Object − A unique instance of a data
focuses on writing the reusable code. It is a widespread
structure that's defined by its class. An
technique to solve the problem by creating objects.
object comprises both data members (class
Major principles of object-oriented programming system are variables and instance variables) and
given below. methods.
o Class  Operator overloading − The assignment of
o Object more than one function to a particular
o Method operator.
o Inheritance
o Polymorphism Class
o Data Abstraction
o Encapsulation The class can be defined as a collection of objects. It is a
logical entity that has some specific attributes and methods.
For example: if you have an employee class, then it should
Overview of OOP Terminology contain an attribute and method, i.e. an email id, name, age,
 Class − A user-defined prototype for an salary, etc.
object that defines a set of attributes that
characterize any object of the class. The Syntax
1. class ClassName:
attributes are data members (class variables 2. <statement-1>
and instance variables) and methods, 3. .
accessed via dot notation. 4. .
5. <statement-N>
 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 Object
class's methods. Class variables are not used
as frequently as instance variables are. The object is an entity that has state and behavior. It may be
any real-world object like the mouse, keyboard, chair, table,
 Data member − A class variable or instance pen, etc.
variable that holds data associated with a
class and its objects. Everything in Python is an object, and almost everything has
attributes and methods. All functions have a built-in attribute
 Function overloading − The assignment of __doc__, which returns the docstring defined in the function
more than one behavior to a particular source code.
function. The operation performed varies by
the types of objects or arguments involved. When we define a class, it needs to create an object to
allocate the memory.
 Instance variable − A variable that is
defined inside a method and belongs only to Example:
the current instance of a class. 1. class car:
 Inheritance − The transfer of the 2. def __init__(self,modelname, year):
3. self.modelname = modelname
characteristics of a class to other classes that 4. self.year = year
are derived from it.

[By.- Prof. Narendra Kumar_CSE] Page 7


[Unit 4]
5. def display(self): emp1.age = 8 # Modify 'age' attribute.
6. print(self.modelname,self.year) del emp1.age # Delete 'age' attribute.
7. c1 = car("Toyota", 2016) Instead of using the normal statements to access
8. c1.display()
attributes, you can use the following functions −
 The getattr(obj, name[, default]) − to
Output:
Toyota 2016 access the attribute of object.
 The hasattr(obj,name) − to check if an
attribute exists or not.
Creating Instance Objects  The setattr(obj,name,value) − to set an
To create instances of a class, you call the class attribute. If attribute does not exist, then it
using class name and pass in whatever arguments would be created.
its __init__ method accepts.  The delattr(obj, name) − to delete an
"This would create first object of Employee class" attribute.
emp1 = Employee("Zara", 2000) hasattr(emp1, 'age') # Returns true if 'age' attribute
"This would create second object of Employee class" exists
emp2 = Employee("Manni", 5000) getattr(emp1, 'age') # Returns value of 'age' attribute
Accessing Attributes setattr(emp1, 'age', 8) # Set attribute 'age' at 8
You access the object's attributes using the dot delattr(empl, 'age') # Delete attribute 'age'
operator with object. Class variable would be Built-In Class Attributes
accessed using class name as follows − Every Python class keeps following built-in
emp1.displayEmployee() attributes and they can be accessed using dot
emp2.displayEmployee() operator like any other attribute −
print "Total Employee %d" % Employee.empCount  __dict__ − Dictionary containing the class's
Now, putting all the concepts together − namespace.
#!/usr/bin/python  __doc__ − Class documentation string or
class Employee: none, if undefined.
'Common base class for all employees'  __name__ − Class name.
empCount = 0  __module__ − Module name in which the
def __init__(self, name, salary): class is defined. This attribute is "__main__"
self.name = name
in interactive mode.
self.salary = salary
 __bases__ − A possibly empty tuple
Employee.empCount += 1
containing the base classes, in the order of
def displayCount(self):
print "Total Employee %d" % Employee.empCount their occurrence in the base class list.
def displayEmployee(self): For the above class let us try to access all these
print "Name : ", self.name, ", Salary: ", self.salary attributes −
"This would create first object of Employee class" #!/usr/bin/python
emp1 = Employee("Zara", 2000) class Employee:
"This would create second object of Employee class" 'Common base class for all employees'
emp2 = Employee("Manni", 5000) empCount = 0
emp1.displayEmployee() def __init__(self, name, salary):
emp2.displayEmployee() self.name = name
print "Total Employee %d" % Employee.empCount self.salary = salary
When the above code is executed, it produces the Employee.empCount += 1
following result − def displayCount(self):
Name : Zara ,Salary: 2000 print "Total Employee %d" % Employee.empCount
Name : Manni ,Salary: 5000 def displayEmployee(self):
Total Employee 2 print "Name : ", self.name, ", Salary: ", self.salary
You can add, remove, or modify attributes of print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
classes and objects at any time −
print "Employee.__module__:",
emp1.age = 7 # Add an 'age' attribute.
Employee.__module__

[By.- Prof. Narendra Kumar_CSE] Page 8


[Unit 4]

print "Employee.__bases__:", Employee.__bases__ self.y = y


print "Employee.__dict__:", Employee.__dict__ def __del__(self):
class_name = self.__class__.__name__
When the above code is executed, it produces the
print class_name, "destroyed"
following result −
pt1 = Point()
Employee.__doc__: Common base class for all
pt2 = pt1
employees
pt3 = pt1
Employee.__name__: Employee
print id(pt1), id(pt2), id(pt3) # prints the ids of the
Employee.__module__: __main__
obejcts
Employee.__bases__: ()
del pt1
Employee.__dict__: {'__module__': '__main__',
del pt2
'displayCount':
del pt3
<function displayCount at 0xb7c84994>, 'empCount':
2, 'displayEmployee': <function displayEmployee at When the above code is executed, it produces
0xb7c8441c>, following result −
'__doc__': 'Common base class for all employees', 3083401324 3083401324 3083401324
'__init__': <function __init__ at 0xb7c846bc>} Point destroyed
Note − Ideally, you should define your classes in
separate file, then you should import them in your
Destroying Objects (Garbage Collection) main program file using import statement.
Python deletes unneeded objects (built-in types or
class instances) automatically to free the memory
space. The process by which Python periodically Class Inheritance
reclaims blocks of memory that no longer are in use Instead of starting from scratch, you can create a
is termed Garbage Collection. class by deriving it from a preexisting class by
Python's garbage collector runs during program listing the parent class in parentheses after the new
execution and is triggered when an object's class name.
reference count reaches zero. An object's reference The child class inherits the attributes of its parent
count changes as the number of aliases that point to class, and you can use those attributes as if they
it changes. were defined in the child class. A child class can
An object's reference count increases when it is also override data members and methods from the
assigned a new name or placed in a container (list, parent.
tuple, or dictionary). Syntax
a = 40 # Create object <40> Derived classes are declared much like their parent
b=a # Increase ref. count of <40> class; however, a list of base classes to inherit from
c = [b] # Increase ref. count of <40> is given after the class name −
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40> class SubClassName (ParentClass1[, ParentClass2,
c[0] = -1 # Decrease ref. count of <40> ...]):
You normally will not notice when the garbage 'Optional class documentation string'
collector destroys an orphaned instance and class_suite
reclaims its space. But a class can implement the Example
special method __del__(), called a destructor, that is #!/usr/bin/python
invoked when the instance is about to be destroyed. class Parent: # define parent class
This method might be used to clean up any non- parentAttr = 100
memory resources used by an instance. def __init__(self):
Example print "Calling parent constructor"
This __del__() destructor prints the class name of def parentMethod(self):
an instance that is about to be destroyed − print 'Calling parent method'
def setAttr(self, attr):
#!/usr/bin/python
Parent.parentAttr = attr
class Point:
def getAttr(self):
def __init__( self, x=0, y=0):
print "Parent attribute :", Parent.parentAttr
self.x = x

[By.- Prof. Narendra Kumar_CSE] Page 9


[Unit 4]

class Child(Parent): # define child class When the above code is executed, it produces the
def __init__(self): following result −
print "Calling child constructor" Calling child method
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child Base Overloading Methods
c.childMethod() # child calls its method Following table lists some generic functionality that
c.parentMethod() # calls parent's method you can override in your own classes −
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method Sr.No. Method, Description & Sample Call
When the above code is executed, it produces the
1 __init__ ( self [,args...] )
following result −
Calling child constructor Constructor (with any optional arguments)
Calling child method Sample Call : obj = className(args)
Calling parent method
2 __del__( self )
Parent attribute : 200
Similar way, you can drive a class from multiple Destructor, deletes an object
parent classes as follows − Sample Call : del obj
class A: # define your class A
3 __repr__( self )
.....
class B: # define your class B Evaluable string representation
..... Sample Call : repr(obj)
class C(A, B): # subclass of A and B
..... 4 __str__( self )
You can use issubclass() or isinstance() functions to Printable string representation
check a relationships of two classes and instances. Sample Call : str(obj)
 The issubclass(sub, sup) boolean function
5 __cmp__ ( self, x )
returns true if the given subclass sub is
indeed a subclass of the superclass sup. Object comparison
 The isinstance(obj, Class) boolean function
Sample Call : cmp(obj, x)
returns true if obj is an instance of
class Class or is an instance of a subclass of
Class Overloading Operators
Suppose you have created a Vector class to
represent two-dimensional vectors, what happens
Overriding Methods when you use the plus operator to add them? Most
You can always override your parent class methods. likely Python will yell at you.
One reason for overriding parent's methods is You could, however, define the __add__ method in
because you may want special or different your class to perform vector addition and then the
functionality in your subclass. plus operator would behave as per expectation −
Example Example
#!/usr/bin/python #!/usr/bin/python
class Parent: # define parent class class Vector:
def myMethod(self): def __init__(self, a, b):
print 'Calling parent method' self.a = a
class Child(Parent): # define child class self.b = b
def myMethod(self): def __str__(self):
print 'Calling child method' return 'Vector (%d, %d)' % (self.a, self.b)
c = Child() # instance of child def __add__(self,other):
c.myMethod() # child calls overridden method return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)

[By.- Prof. Narendra Kumar_CSE] Page 10


[Unit 4]

v2 = Vector(5,-2)
print v1 + v2
When the above code is executed, it produces the
following result −
Vector(7,8)

Data Hiding
An object's attributes may or may not be visible
outside the class definition. You need to name
attributes with a double underscore prefix, and
those attributes then are not be directly visible to
outsiders.
Example
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
When the above code is executed, it produces the
following result −
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute
'__secretCount'
Python protects those members by internally
changing the name to include the class name. You
can access such attributes
as object._className__attrName. If you would
replace your last line as following, then it works for
you −
print counter._JustCounter__secretCount
When the above code is executed result −
1
2
2

[By.- Prof. Narendra Kumar_CSE] Page 11

You might also like