0% found this document useful (0 votes)
13 views52 pages

4A - Objects

This document covers the fundamentals of Python objects, focusing on definitions, mechanics, and object-oriented programming concepts such as classes, methods, attributes, and inheritance. It emphasizes the importance of understanding how objects work together within a program and introduces the lifecycle of objects, including constructors and destructors. The document also provides examples of creating and using classes and instances in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views52 pages

4A - Objects

This document covers the fundamentals of Python objects, focusing on definitions, mechanics, and object-oriented programming concepts such as classes, methods, attributes, and inheritance. It emphasizes the importance of understanding how objects work together within a program and introduces the lifecycle of objects, including constructors and destructors. The document also provides examples of creating and using classes and instances in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Objects

Unit - 4A

Python for Everybody: Chapter 14


Warning
• This lecture is very much about definitions and
mechanics for objects
• This lecture is a lot more about “how it works” and less
about “how you use it”
• You won’t get the entire picture until this is all looked at
in the context of a real problem
• So please suspend disbelief and learn technique for the
next 40 or so slides…
[Link]
[Link]
Lets Start with Programs
Indian floor? 0
inp = input('Indian 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).

[Link]
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.

[Link]
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.

[Link]
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
This is the template
class is a reserved
class PartyAnimal: for making
word
x=0 PartyAnimal objects

def party(self) : Each PartyAnimal


Each PartyAnimal
self.x = self.x + 1 object has a bit of
object has a bit of
print("So far",self.x) data
code
Construct a
an = PartyAnimal() PartyAnimal object
and store in an
[Link]()
Tell the an object [Link]() [Link](an)
to run the party() [Link]()
code within it
class PartyAnimal: $ python [Link]
x=0

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

an = PartyAnimal()

[Link]()
[Link]()
[Link]()
class PartyAnimal:
$ python [Link]
x=0

def party(self) :
self.x = self.x + 1
print("So far",self.x)
an
x 0
an = PartyAnimal()
party()
[Link]()
[Link]()
[Link]()
class PartyAnimal: $ python [Link]
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()
[Link]()
[Link]()
[Link]() [Link](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 '__contains__', '__delattr__',
'__delitem__', '__delslice__',
'__doc__', … '__setitem__',
• The rest are real operations that '__setslice__', '__str__',
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:
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 [Link]
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
[Link]
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:
x = 0

def __init__(self): $ python [Link]


print('I am constructed')
I am constructed
def party(self) : So far 1
self.x = self.x + 1 So far 2
print('So far',self.x) I am destructed 2
an contains 42
def __del__(self):
print('I am destructed', self.x)

an = PartyAnimal()
[Link]()
The constructor and destructor are
[Link]() optional. The constructor is
typically used to set up variables.
The destructor is seldom used.
an = 42
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

[Link]
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:
x = 0 additional parameters.
name = "" These can be used to set up
def __init__(self, z): instance variables for the
[Link] = z
particular instance of the
print([Link],"constructed")
class (i.e., for the particular
def party(self) : object).
self.x = self.x + 1
print([Link],"party count",self.x)

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

[Link]()
[Link]()
[Link]() [Link]
class PartyAnimal:
x = 0
name = ""
def __init__(self, z):
[Link] = z
print([Link],"constructed")

def party(self) :
self.x = self.x + 1
print([Link],"party count",self.x)

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

[Link]()
[Link]()
[Link]()
class PartyAnimal:
x = 0
name = "" s
def __init__(self, z): x: 0
[Link] = z
print([Link],"constructed")
name:
def party(self) :
self.x = self.x + 1
print([Link],"party count",self.x)

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

[Link]()
[Link]()
[Link]()
class PartyAnimal:
x = 0
name = "" s
def __init__(self, z): x: 0
[Link] = z
print([Link],"constructed")
name: Sally
def party(self) :
self.x = self.x + 1
print([Link],"party count",self.x)

s = PartyAnimal("Sally") j
j = PartyAnimal("Jim") x: 0
We have two
[Link]()
[Link]()
independent name: Jim
[Link]() instances
class PartyAnimal:
x = 0
name = "" Sally constructed
def __init__(self, z): Jim constructed
[Link] = z Sally party count 1
Jim party count 1
print([Link],"constructed") Sally party count 2

def party(self) :
self.x = self.x + 1
print([Link],"party count",self.x)

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

[Link]()
[Link]()
[Link]()
Inheritance/Dervied
[Link]
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.

[Link]
class PartyAnimal:
x = 0 s = PartyAnimal("Sally")
name = "" [Link]()
def __init__(self, nam):
[Link] = nam j = FootballFan("Jim")
print([Link],"constructed") [Link]()
[Link]()
def party(self) :
self.x = self.x + 1
print([Link],"party count",self.x)
FootballFan is a class which
class FootballFan(PartyAnimal): extends PartyAnimal. It has all
points = 0
the capabilities of PartyAnimal
def touchdown(self):
[Link] = [Link] + 7 and more.
[Link]()
print([Link],"points",[Link])
class PartyAnimal:
x = 0 s = PartyAnimal("Sally")
name = "" [Link]()
def __init__(self, nam):
[Link] = nam j = FootballFan("Jim")
print([Link],"constructed") [Link]()
[Link]()
def party(self) :
self.x = self.x + 1
print([Link],"party count",self.x) s
x:
class FootballFan(PartyAnimal):
points = 0
name: Sally
def touchdown(self):
[Link] = [Link] + 7
[Link]()
print([Link],"points",[Link])
class PartyAnimal:
x = 0 s = PartyAnimal("Sally")
name = "" [Link]()
def __init__(self, nam):
[Link] = nam j = FootballFan("Jim")
print([Link],"constructed") [Link]()
[Link]()
def party(self) :
self.x = self.x + 1
print([Link],"party count",self.x) j
x:
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
name: Jim
[Link] = [Link] + 7
[Link]() points:
print([Link],"points",[Link])
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
Additional Source Information
•Snowman Cookie Cutter" by Didriks is licensed under CC BY
[Link]

•Photo from the television program Lassie. Lassie watches as Jeff (Tommy Rettig) works on his bike is Public
Domain
[Link]
ayPython is a multi paradigm programming language

4 One of the approach is the oops

Two characters
Object
data a Attribute Instance
Gnuction by Turchi etc
Breed
colour Height
Dog as
Description of the object
Activity
Barking Dancing
Dog
which are not repeated
Set of syntax
OOP in Python
DRY Don't repeatYousef
Concept

class Description of
the object I Properties
labels

to define the dos


Syntax

É Ee
Keyword

initiationof a class When a

object Instance of
class is defined
the object is described
ÉÉ dog Definingthe class
das attribute Access to it attributes

q [Link]
instance attributes

def fit self name age


name
Descriptions
self name

self age age


defined
A initialize the des
Aravind 8
dogs dog
dogs dog Tommy 6

Accening the
class attributes
[Link]
format dogt das
print Aravind
is a
das [Link]
print Tommy
is a 1 formatfdogzi
is a animal
Aravind
Of Tommy is a animal

the instance description


Accessing
aged
Cy is years format [Link] dogs
format akane dotes
print
print Ey is 13
yeas

Aravind is 8years
Of
Tommy is G years
methodcreating a from the aims
nod
The newly formed
without any modifications
of child do
class is called as
deredday
class Parent das Base day
Existing
class child des
Meydeived
Multiple inheritance
class Parentclass
parentclass statements
do
the parent dad
Body of class damned
Deed das Parent do a
class
desired class I
Body of the class denied class
Parent
do
parent class

des deledda 3
def init self
man des
print Bird is
defined t Parents Parent

Lef iii swim self


swim t
print It can

child class

init self child day


def
t
chid
des def run self
print It can run't

ann swim
n

Accening is
restricted pud
modification
private Prevent the use of data from
This is called as encapsulation
the
denote the private
attributes by using
We double
underscore ie single's or

a 20 data Ivan ale

aself É b
s am

print
printfelt a

LIFE app Encepl


app a u print app s
appidiepf
01ps 20
Welcome to Bengaluru
welcome to Bengaluru
Neo outputs
20
Accented class methods
Variable is public
Variable is private do
be accened outside
Variable is Restricted cant

returns
Employee Name Age Salary IT

Employee 7 Name Age


A
counts staff Salary It returns

a y
e

def init self


nÉÉÉÉÉÉiJ das method
public elf name name
self salary salay
private selfpig 9
day
pride def show self
Jet
name and is
none of Employee is self
Restricted

salary is self salary


x

outride des
3500
emp Employee Aravind

print [Link] Attribute Error


X
Anthony
Polymorphism poly many morphismform

Code to calculate
areas

Clas Circle
pi 3.14157
radius
def init self radius
self radius
radius selfradius
area self pix self
are

You might also like