Module 5 Python Final
Module 5 Python Final
By
Naveen Kumar .V
Programmer-defined types
Class :-It the blueprint or template that specifies what data and
functions should be included in the objects.
.
Object :- An object is an identifiable real world entity with
some characteristics and behaviour.
Example :- Class point
The body is a docstring that explains what the class is used for.
Object Creation :- instantiation
The variable blank refers to a object point, which contains two attributes.
Each attribute refers to a floating-point number.
Point Object
Two syntaxes are shown with and without using a format specifiers.
Syntax -1
print ('The value of element x is: ‘, blank.x)
print ('The value of element y is: ‘, blank.y)
Output
The value of element x is: 3.0
The value of element y is: 4.0
Syntax -2
print('The value of element x is %g \n The value of element y is %g' %
(blank.x, blank.y))
Output:
The value of element x is 3
The value of element y is 4
Example:- passes box as argument and assigns the resulting Point to center
Objects are mutable
Eg: - grow_rectangle()
Takes a Rectangle object and two numbers, dwidth & dheight
Adds the numbers to the width and height of the rectangle
Copying
copy module:- Contains copy function that can duplicate any object
shallow copy
shallow copy
it copies the object and any references it contains, but not the
embedded objects.
deepcopy
pure function : -Does not modify any of the objects passed as arguments
In this case, the insight is that a Time object is really a three digit
number in base 60.
Object-oriented features
Programs include class and method definitions.
Most computation expressed :- As operations on objects.
Objects often represent things in the real world
methods often corresponds to ways things in the real world interact.
The init method (short for “initialization”) is a special method that gets
invoked when an object is instantiated.
Its full name is _ _init_ _.
An init method for the Time class might look like this:
self.hour = hour stores the value of the parameter hour as an attribute of self.
Eg:- if you define a method named _ _add_ _ for the Time class,
you can use the + operator on Time objects.
Add invoked
Str invoked
When applying + operator to Time objects python invokes _ _add_ _.
When you print the result Python invokes _ _str_ _.
Eg:- the built-in function sum ( ) , which adds the elements of a sequence,
works as long as the elements of the sequence support addition.
Since Time objects provide internally an _add_ method, they work with
sum ( ) :
methods a class provides :- should not depend on how the attributes are
represented.
Eg:- class that represents a time of day.
Methods provided by this class include:- time_to_int() ,
is_after() , add_time () .
We could implement those methods in several ways.