0 ratings 0% found this document useful (0 votes) 35 views 17 pages Advanced Python
First of all I really thankful to my Lovely Professional University because of them 1 could achieve the target. I express my sincere thanks to my project guide Mrs. Deepika Dhall who had guide to me throughout my project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Advanced python For Later CLASSES AND
OBJECTS
‘e know that a class is a model or plan to create objects. This means, we e write a
class with the attributes and actions of objects. Attributes are represented by
variables and actions are performed by methods. So, a class contains variable
and methods. The same variables and methods are also available in the objects because
tiey'are created from the class. These variables are also called ‘Snstance variables’
because they are created inside the instance (i.e. object).
Please remember the difference between a function and a method. A function written
inside a class is called a method. Generally, a method is called using one of the following
two ways:
5 classname.methodname()
a instancename.methodname()
The general format of a class is given as follows:
Class ,lassnate (object)
docstring describing the class
attributes Z
—init_(self):
det methodi():"~ 2
def method2()
“eating aClass-
iter wt is created with the keyword class and then writing the classname,
Classname, ‘object’ is written inside the Classname. This “object
* the base class name from where all classes in Python are derived
Sw" own classes are also derived from ‘object’ clas es) Hence, we &
Teprese
Bye ni352 | Chapter 13
mention ‘object’ in
since it is implied.
te that writing ‘object? j
es. Please no} ee 18 not
paren —
— /
ich is written using triple double quotes
ing is a string which is wr i :
The dc tsog ie the complete description about the class and its usage,
quotes that gi =
oF triple
|
hence it is optional. ‘attributes’ an tin’
; nee i : are ny
tation file and he eee attire thi,
used to create socom init_{self] is a special method to initialize qe Tara
variables tbat ie etc. are methods that are intended to process variableg—"
method1() and met _—
. rite code in the class that specifi
Hewe)take ee ey ony. student. For example, a atudent has attityn
oa ‘name, te 7 etc. These attributes should be written “Inside
suaedena oa variables. Similarly, a student can perform actions jy
ae eading, etc. These actions should be represénted by thethods
toe Seen dese Soe class Student contains these attributes and actions
shown here:
ies the Attrib
is: bject):
Student: # another way is: class Student(ol
ye block defines attributes
def init__(self):
self.name = ‘Vishnu
self.age = 20
self.marks = 900
# the below block defines a method
def talk(self): —
printC’Hi, I am ‘, self.name)
print(’My age is’
» Self.age’
print(‘my marks are’, sai teanesy
Observe that the keyword class is use
the class name. So, ‘Student’ is our
with a capital letter, hence ‘S’ is cay
and_methods. Sin
ed_to declare a class. After this, we Sea
class name. Generally, a class name should S
; Pital in ‘Student’. In the class, we write atrit’
se in Python, we cannot declare variables, we have wile |
is method is useful to initial”
> w
; eal
ually defined and we cannot
meter ‘Self Written after the method name”.
an instance for the Student elas't "TS to ie
and that memory location ig 19°" 2 Separate me: ted on the
variables ‘name’, ‘age’, ney Gefault stored ne ee ' ae contait
instance variables, ew pode one
no refet
We can use 8re called i iables. TO" y
: ven if s h instance varia ach sell
self.name’, ‘self.age’ and Self.marks: Ct operator Notation along with §
OP erate e
jee the method talki), Thy,
. S Meth
method displays the values of the wae kes the ‘seip
es Teferrj,
Ting ¢
peter
variable as para™
em using ‘self’.nd Objects] 353
sre methods that act on instances (or objects) of a class are called instance methods,
Ys methods use ‘self as the first parameter that refers to thé location of the
stance TS smory. Since i
ance in the memory. Since instance methods know the location of instance. they can
t_(self) and
eihe instance variables. In the previous code, the two methods _j
“elf are called instance methods.
walks oa
gent class, a student is talking to us through talk() method. He is introducing
us, as shown here:
tn the StU
pimself to
wi, I am Vishnu
wy age is 20
ty marks are 900
ris ig what the talk() method displays. Writing a class like this is not_sufficie
fe
ir should be used. To use a class, we should create an instance (or object) to the
cass Instance creation represents allotting memory necessary to store the actual data
Vishnu, 20 and 900. To create an instance, the following syntax is
of the variables, i
used:
instancename = Classname(
0, to create an instance (or object) to the Student class, we can write as:
sl = student)
Here, ‘s1’ is nothing but the instance name. When we create an instance like this, the
following steps will take place internally:
1. First of all, a block of memory is allocated on heap. How much memory
is to be allocated is decided from the attributes and methods available in the
Student class.
2. After allocating the memory block, the special method by the name ‘i +_(selff’ is
called internally. This method stores the initial data into the variables. Since thi
method is useful to construct the instance, it is called ‘constructor’.
; useful to construct the instance, itis ¢
3. Finally, the allocated memory location address of the instance is returned into ‘SI’
variable. To see this memory location in decimal number format, we can use id()
function as id(s1).
fe ‘SI’ refers to the instance of the Student class. Hence any variables or methods in
instance can be referenced by ‘s1’ using dot operator as:
ive. vishnu
Si-name # this refers to data in name variable. i.e
cger # this refers to data in age variable, i.e. 20
Shmarks # this refers to data in marks variable, 1-e. 900
stalkQ # this calls the talkQ) method=~
354 {6
he dot operator takes the instance name at its left and the member of the j
ie ¢ 13.1 shows how ‘s1’ instance of Student clagg ; Ntanee
the right hand side, Figur ineren
in
memory:
attributes
nari (eam)
a -+——-
def _Inlt_(self):
methods
student()
Figure 13.1: Student class instance in memory
Program 1: A Python program to define Student class and create an object to it, Also, we
will call the method and display the student's details.
# instance variables and instance method
class Student:
# this is a special method called constructor.
def _init_(self):
self.name = ‘Vishnu!
self.age = 20
self.marks = 900
# this is an instance method.
def talk(self):
prime cis I am', self.name)
print(’my age is', self.age)
print('my marks are', self.marks)
# create an instance to Student c
sl = Student() ee
# cal] the method i
sr talkO jod using the instance.
Output:
C:\>python cl.
Hi, I am Vishny,
My age is 20
My marks are 900Classes and Objects | 355
program 1, we used the ‘self variable to refer to the instance of the same class. Also,
In Prot
sed a special method ‘_init_(self)’ that initializes the variables of the instance. Let’s
oy more clarity on these two concepts,
ha
the Self Variable
‘gl? is a default variable that contains the memory address of the instance of the current
class. So, We can use ‘self’ to refer to all the instance variables and instance methods.
When an instance to the class is created, the instance name contains the memory
location of the instance. This memory location is internally passed to ‘self. For example,
we create an instance to Student class as:
sl'= StudentQ)
Here, ‘sl’ contains the memory address of the instance. This memory address is
intemally and by default passed to ‘self variable. Since ‘self’ knows the memor
ofthe instance, it can refer to all the members of the instance. We use ‘self’ in
2 The ‘self variable is used as first parameter in the constructor as:
def init__(self):
In this case, ‘self can be used to refer to the instance variables inside the
constructor.
‘self can be used as first parameter in the instance methods as:
def talk(self):
Here, talk() is instance method as it acts on the instance variables. If this method
wants to act on the instance variables, it should know the memory location of the
instance variables. That memory location is by default available to the talk() method
through ‘self.
Constructor
‘ constructor is a special method that is used to initialize the instance variables of a
Glass. In the constructor, we create the instance variabl
and initialize them with some
Saning values. The first parameter of the constructor will be ‘self’ iable that contains
© memory address of the instance. For example, a
def =init_(self):
self.name = ‘Vishnu’
self.marks = 900
» the co;
‘selfmarks, y
the time of
an instance
Here,
nstructor_has only one parameter, i.e. ‘self. Using ‘self.name’ and
Me can access the instance variables of the class. A_constructor is called at
“reating an instance. So, the above constructor will be called when we create
e as: hme em
SUS student