Module 3
Module 3
Syntax
class <class name> : // class body
The class construct starts with the keyword, class, followed by the
name of the class, a colon(:), and then an indented block of code also
known as the body of the class.
Definitions:
• Classes : the blueprint of objects, template or a backbone ex. Car class
• Objects: the actual entity we interact with, the instance of the class ex.
2years, black, German, VW.
• Attribute: the object characteristic ex. Colour, length, height, N-cap rating
etc
• Method : the actions(functions) that the object can do.
CALSS VS INSTANCE ATTRIBIUTES
Class car:
• The attributes inside the __init__ method are def __init__(self, olor,year,model)
specified for the instance self.color = color
self.year = year
• Attributes that are shared between all instances self.model = model
no_wheels = 4
are called as class attributes and are defined
outside the init method
ACTIVITY
Object
String
Objects get
created and
used Output
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects are
bits of code
and data Output
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects hide detail
- they allow us to
ignore the detail of
the “rest of the Output
program”.
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects hide detail -
they allow the “rest
of the program” to
ignore the detail Output
about “us”.
Definitions
• Class - a template
• Method or Message - A defined capability of a class
• Field or attribute- A bit of data in a class
• Object or Instance - A particular instance of a class
Terminology: Class
Defines the abstract characteristics of a thing (object), including the
thing's characteristics (its attributes, fields or properties) and the
thing's behaviors (the things it can do, or methods, operations or
features). One might say that a class is a blueprint or factory that
describes the nature of something. For example, the class Dog would
consist of traits shared by all dogs, such as breed and fur color
(characteristics), and the ability to bark and sit (behaviors).
Terminology: Instance
One can have an instance of a class or a particular object.
The instance is the actual object created at runtime. In
programmer jargon, the Lassie object is an instance of the
Dog class. The set of values of the attributes of a particular
object is called its state. The object consists of state and the
behavior that's defined in the object's class.
Object and Instance are often used interchangeably.
http://en.wikipedia.org/wiki/Object-oriented_programming
Terminology: Method
An object's abilities. In language, methods are verbs. Lassie, being a
Dog, has the ability to bark. So bark() is one of Lassie's methods. She
may have other methods as well, for example sit() or eat() or walk() or
save_timmy(). Within the program, using a method usually affects
only one particular object; all Dogs can bark, but you need only one
particular dog to do the barking
http://en.wikipedia.org/wiki/Object-oriented_programming
SOME PYTHON OBJECTS
>>> dir(x)
>>> x = 'abc' [ … 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
>>> type(x) 'find', 'format', … 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
<class 'str'> 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
>>> type(2.5) 'swapcase', 'title', 'translate', 'upper', 'zfill']
<class 'float'> >>> dir(y)
>>> type(2) [… 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
<class 'int'> 'reverse', 'sort']
>>> y = list() >>> dir(z)
>>> type(y) […, 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem',
<class 'list'> 'setdefault', 'update', 'values']
>>> z = dict()
>>> type(z)
<class 'dict'>
A Sample Class
This is the template
class is a reserved
class PartyAnimal: for making
word
x=0 PartyAnimal objects
def party(self) :
self.x = self.x + 1
print("So far",self.x)
an = PartyAnimal()
an.party()
an.party()
an.party()
class PartyAnimal:
$ python party1.py
x=0
def party(self) :
self.x = self.x + 1
print("So far",self.x)
an
an = PartyAnimal()
x 0
party()
an.party()
an.party()
an.party()
class PartyAnimal: $ python party1.py
x=0 So far 1
So far 2
def party(self) : So far 3
self.x = self.x + 1
print("So far",self.x)
an
self x
an = PartyAnimal()
party()
an.party()
an.party()
an.party() PartyAnimal.party(an)
Playing with dir() and type()
A Nerdy Way to Find Capabilities
• The dir() command lists capabilities >>> y = list()
>>> type(y)
• Ignore the ones with underscores - <class 'list'>
these are used by Python itself >>> dir(y)
['__add__', '__class__', '__contains__',
'__delattr__', '__delitem__', '__delslice__',
• The rest are real operations that the '__doc__', … '__setitem__', '__setslice__',
object can perform '__str__', 'append', 'clear', 'copy', 'count',
'extend', 'index', 'insert', 'pop', 'remove',
• It is like type() - it tells us something 'reverse', 'sort']
>>>
*about* a variable
class PartyAnimal:
x=0
We can use dir() to find
the “capabilities” of our
def party(self) : newly created class.
self.x = self.x + 1
print("So far",self.x)
an = PartyAnimal()
$ python party3.py
print("Type", type(an)) Type <class '__main__.PartyAnimal'>
print("Dir ", dir(an)) Dir ['__class__', ... 'party', 'x']
Try dir() with a String
>>> x = 'Hello there'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__',
'__init__', '__le__', '__len__', '__lt__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__',
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
Object LifeCycle
http://en.wikipedia.org/wiki/Constructor_(computer_science)
Object LifeCycle
• Objects are created, used, and discarded
• We have special blocks of code (methods) that get called
- At the moment of creation (constructor)
- At the moment of destruction (destructor)
• Constructors are used a lot
• Destructors are seldom used
Constructor
The primary purpose of the constructor is to set up some
instance variables to have the proper initial values when the
object is created
SELF KEYWORD
•Self keyword : when we initialize two or
more objects of same class python need a
• The first argument must be self
• The attributes are accessed by
way to differentiate between them.
using the “ .” operator
•It’s a pointer to the memory location/address • Ex.
where each object of class is stored.
def __init__(self, color, year, model):
•Init method self.color = color
•Stores initial values for all instance self.year = year
attributes self. Model = model
•It must be created like __init__()
class add_sub:
def __init__(self, x, y): OUTPUT
self.x = x 10 + 6 = 16
self.y = y
# define 'add' method 10 - 6 = 4
def add(self):
return self.x + self.y
# define 'subtract' method
def subtract(self): • The __init__ method is reserved in Python,
return self.x - self.y
also known as a constructor, it is called each
if __name__ == '__main__': time when an object or instance is created
x = 10
y = 6
from a class. It is commonly used to
# create an instance initialize the attributes of the class for the
opp = add_sub(x,y) created object.
• Each method of the class has the self-
# call add method
print(f'{x} + {y} = {opp.add()}') identifier, which identifies the instance upon
#print(opp.add()) which a method is invoked. This allows us to
# call subtract method
create as many objects of a class as we wish.
print(f'{x} - {y} = {opp.subtract()}')
class PartyAnimal:
x=0
$ python party4.py
def __init__(self):
I am constructed
print('I am constructed')
So far 1
def party(self) : So far 2
self.x = self.x + 1 I am destructed 2
print('So far',self.x) an contains 42
def __del__(self):
print('I am destructed', self.x)
an = PartyAnimal()
The constructor and destructor are
an.party() optional. The constructor is
an.party() typically used to set up variables.
an = 42 The destructor is seldom used.
print('an contains',an)
Constructor
In object oriented programming, a constructor in a class is a
special block of statements called when an object is created
http://en.wikipedia.org/wiki/Constructor_(computer_science)
ACTIVITY 2:
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party() party5.py
class PartyAnimal:
x=0
name = ""
def __init__(self, z):
self.name = z
print(self.name,"constructed")
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party()
class PartyAnimal:
x=0
name = "" s
def __init__(self, z): x: 0
self.name = z
print(self.name,"constructed")
name:
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party()
class PartyAnimal:
x=0
name = "" s
def __init__(self, z): x: 0
self.name = z
print(self.name,"constructed")
name: Sally
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally") j
j = PartyAnimal("Jim") x: 0
We have two
s.party()
j.party()
independent name: Jim
s.party() instances
class PartyAnimal:
x=0
name = "" Sally constructed
def __init__(self, z): Jim constructed
self.name = z Sally party count 1
Jim party count 1
print(self.name,"constructed") Sally party count 2
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party()
Inheritance
Inheritance
• When we make a new class - we can reuse an existing
class and inherit all the capabilities of an existing class and
then add our own little bit to make our new class
• Another form of store and reuse
• Write once - reuse many times
• The new class (child) has all the capabilities of the old
class (parent) - and then some more
Terminology: Inheritance