KEMBAR78
Module 4 OOP | PDF | Class (Computer Programming) | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
6 views42 pages

Module 4 OOP

The document provides an overview of Python objects and object-oriented programming concepts, including classes, instances, methods, and inheritance. It emphasizes the importance of breaking problems into smaller parts and how objects encapsulate code and data, allowing for code reuse and organization. Additionally, it explains the lifecycle of objects, constructors, and the ability to create multiple instances of classes.

Uploaded by

Erdey Syoum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views42 pages

Module 4 OOP

The document provides an overview of Python objects and object-oriented programming concepts, including classes, instances, methods, and inheritance. It emphasizes the importance of breaking problems into smaller parts and how objects encapsulate code and data, allowing for code reuse and organization. Additionally, it explains the lifecycle of objects, constructors, and the ability to create multiple instances of classes.

Uploaded by

Erdey Syoum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Python Objects

Lets Start with Programs


Europe floor? 0
inp = input('Europe floor?') US floor 1
usf = int(inp) + 1
print('US floor', usf)

Input Process Output


Object Oriented
• A program is made up of many cooperating objects
• Instead of being the “whole program” - each object is a
little “island” within the program and cooperatively
working with other objects

• A program is made up of one or more objects working


together - objects make use of each other’s
capabilities
Object
• An Object is a bit of self-contained Code and Data
• A key aspect of the Object approach is to break the
problem into smaller understandable parts (divide and
conquer)
• Objects have boundaries that allow us to ignore un-needed
detail
• We have been using objects all along: String Objects,
Integer Objects, Dictionary Objects, List Objects...
Input
Dictionary
Object

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).

http://en.wikipedia.org/wiki/Object-oriented_programming
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

Method and Message are often used interchangeably.

http://en.wikipedia.org/wiki/Object-oriented_programming
Some Python Objects
>>> dir(x)
>>> x = 'abc' [ … 'capitalize', 'casefold', 'center', 'count',
>>> type(x) 'encode', 'endswith', 'expandtabs', 'find',
<class 'str'> 'format', … 'lower', 'lstrip', 'maketrans',
>>> type(2.5) 'partition', 'replace', 'rfind', 'rindex', 'rjust',
<class 'float'> 'rpartition', 'rsplit', 'rstrip', 'split',
>>> type(2) 'splitlines', 'startswith', 'strip', 'swapcase',
<class 'int'> 'title', 'translate', 'upper', 'zfill']
>>> y = list() >>> dir(y)
>>> type(y) [… 'append', 'clear', 'copy', 'count', 'extend',
<class 'list'> 'index', 'insert', 'pop', 'remove', 'reverse',
>>> z = dict() 'sort']
>>> type(z) >>> dir(z)
<class 'dict'> […, 'clear', 'copy', 'fromkeys', 'get', 'items',
'keys', 'pop', 'popitem', 'setdefault', 'update',
'values']
A Sample Class
class is a reserved When the object is
class PartyAnimal:
word that defines a constructed, a
template for making def __init(self)__: specially named
objects self.x = 0 method is called to
allocate and initialize
Each PartyAnimal def party(self) :
attributes.
object has a bit of self.x = self.x + 1
code print("So far",self.x)
Construct a
an = PartyAnimal() PartyAnimal object
and store in an
an.party()
Tell the an an.party()
an.party() PartyAnimal.party(an)
object to run the
party() code
within it
class PartyAnimal: $ python party2.py
def __init(self)__:
self.x = 0

def party(self) :
self.x = self.x + 1
print("So far",self.x)

an = PartyAnimal()

an.party()
an.party()
an.party()
class PartyAnimal: $ python party2.py
def __init(self)__:
self.x = 0

def party(self) :
self.x = self.x + 1
print("So far",self.x)
an
an = PartyAnimal() x 0
an.party() party()
an.party()
an.party()
class PartyAnimal: $ python party2.py
def __init(self)__:
So far 1
self.x = 0 So far 2
So far 3
def party(self) :
self.x = self.x + 1
print("So far",self.x)
an
an = PartyAnimal() self x

an.party() party()
an.party()
an.party()
PartyAnimal.party(an)
Playing with dir() and type()
A Nerdy Way to Find Capabilities
>>> y = list()
• The dir() command lists
>>> type(y)
capabilities <class 'list'>
>>> dir(y)
• Ignore the ones with underscores ['__add__', '__class__',
- these are used by Python itself '__class_getitem__',
'__contains__', '__delattr__',
'__delitem__', '__dir__',
• The rest are real operations that '__doc__', '__eq__', ...
the object can perform 'append', 'clear', 'copy',
'count', 'extend', 'index',
• It is like type() - it tells us 'insert', 'pop', 'remove',
'reverse', 'sort']
something *about* a variable >>>
class PartyAnimal:
We can use dir() to find
def __init__(self):
self.x = 0 the “capabilities” of our
newly created class.
def party(self) :
self.x = self.x + 1
print("So far",self.x)

an = PartyAnimal()
$ python party3.py
Type <class '__main__.PartyAnimal'>
print("Type", type(an))
Dir ['__class__', ... 'party', 'x']
print("Dir ", dir(an))
Type <class 'int'>
print ("Type", type(an.x))
Type <class 'method'>
print ("Type", type(an.party))

party3.py
Try dir() with a String
>>> x = 'Hello there'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__',
'__getstate__', '__gt__', '__hash__', '__init__',
'__init_subclass__', ...'capitalize', 'casefold', 'center',
'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isascii',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'removesuffix',
'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
class PartyAnimal:

def __init__(self): $ python party4.py


self.x = 0
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)
Many Instances
• We can create lots of objects - the class is the template
for the object
• We can store each distinct object in its own variable
• We call this having multiple instances of the same class
• Each instance has its own copy of the instance variables
Constructors can have
class PartyAnimal:
additional parameters.
def __init__(self, z): These can be used to set up
self.x = 0 instance variables for the
self.name = z
particular instance of the
print(self.name,"constructed")
class (i.e., for the particular
def party(self) : object).
self.x = self.x + 1
print(self.name,"party count",self.x)

s = PartyAnimal("Sally")
s.party()
j = PartyAnimal("Jim")

j.party()
s.party() party5.py
class PartyAnimal:

def __init__(self, z):


self.x = 0
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")
s.party()
j = PartyAnimal("Jim")

j.party()
s.party()
class PartyAnimal:

def __init__(self, z): s


self.x = 0 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")
s.party()
j = PartyAnimal("Jim")

j.party()
s.party()
class PartyAnimal:

def __init__(self, z): s


self.x = 0 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
s.party() x: 0
j = PartyAnimal("Jim")

j.party()
name: Jim
s.party()
class PartyAnimal:

def __init__(self, z): Sally constructed


self.x = 0 Sally party count 1
self.name = z Jim constructed
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")
s.party()
j = PartyAnimal("Jim")

j.party()
s.party()
Inheritance
http://www.ibiblio.org/g2swap/byteofpython/read/inheritance.html
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

‘Subclasses’ are more specialized versions of a class, which


inherit attributes and behaviors from their parent classes, and
can introduce their own.

http://en.wikipedia.org/wiki/Object-oriented_programming
class PartyAnimal:

def __init__(self, nam):


self.x = 0 s = PartyAnimal("Sally")
self.name = nam s.party()
print(self.name,"constructed")
j = FootballFan("Jim")
def party(self) : j.party()
self.x = self.x + 1 j.touchdown()
print(self.name,"party count",self.x)

class FootballFan(PartyAnimal):
FootballFan is a class which
def __init__(self, nam) :
super().__init__(nam) extends PartyAnimal. It has all
self.points = 0 the capabilities of PartyAnimal
and more.
def touchdown(self):
self.points = self.points + 7
self.party() party7.py
print(self.name,"points",self.points)
class PartyAnimal:

def __init__(self, nam):


self.x = 0 s = PartyAnimal("Sally")
self.name = nam s.party()
print(self.name,"constructed")
j = FootballFan("Jim")
def party(self) : j.party()
self.x = self.x + 1 j.touchdown()
print(self.name,"party count",self.x)

class FootballFan(PartyAnimal): s
x:
def __init__(self, nam) :
super().__init__(nam)
self.points = 0 name: Sally
def touchdown(self):
self.points = self.points + 7
self.party()
print(self.name,"points",self.points)
class PartyAnimal:

def __init__(self, nam):


self.x = 0 s = PartyAnimal("Sally")
self.name = nam s.party()
print(self.name,"constructed")
j = FootballFan("Jim")
def party(self) : j.party()
self.x = self.x + 1 j.touchdown()
print(self.name,"party count",self.x)

class FootballFan(PartyAnimal): j
x:
def __init__(self, nam) :
super().__init__(nam)
self.points = 0 name: Jim
def touchdown(self):
self.points = self.points + 7 points:
self.party()
print(self.name,"points",self.points)
Definitions
• Class - a template
• Attribute – A variable within a class
• Method - A function within a class
• Object - A particular instance of a class
• Constructor – Code that runs when an object is created
• Inheritance - The ability to extend a class to make a new class.
Summary
• Object Oriented programming is a very structured
approach to code reuse

• We can group data and functionality together and create


many independent instances of a class

You might also like