Object Oriented Programming
Programming paradigms
• Modules, Data structure and
procedures that operate upon
them
Procedural • Focus on procedure ex: C
• Focus on data
• Solving real world problem
Object Oriented • Example: C++,Java, Python
Overview of OOP Terminology
Class: A user-defined prototype for an object that defines a set
of attributes that characterize any object of the class. The
attributes are data members
It’s a template to create object.
A way to create User defined data type to be able to
represent real world object and hence solve real word problem.
Class variable: A variable that is shared by all instances of a
class. Class variables are defined within a class but outside any
of the class's methods. Class variables are not used as
frequently as instance variables are.
Inheritance: The transfer of the characteristics of a class to
other class. Facilitates Code Reusability and feature
enhancement.
Data member: A class variable or instance variable that holds
data associated with a class and its objects.Classes that are
derived from it.
Overview of OOP Terminology (Contd..)
Instance: An individual object of a certain class. An object obj
that belongs to a class Circle, for example, is an instance of the
class Circle.
Instance variable: A variable that is defined inside a method
and belongs only to the current instance of a class.
Instantiation: The creation of an instance of a class.
Method : A special kind of function that is defined in a class
definition.
Object: A unique instance of a data structure that's defined by
its class. An object comprises both data members class variables
and instance variables and methods.
Encapsulation : Dividing the code into a public interface, and
a private implementation of that interface
Object Oriented Programming
in Python:
Defining Classes
It’s all objects…
Everything in Python is really an object.
• We’ve seen hints of this already…
“hello”.upper()
list3.append(‘a’)
dict2.keys()
• These look like Java or C++ method calls.
• New object classes can easily be defined in
addition to these built-in data-types.
In fact, programming in Python is typically
done in an object oriented fashion.
Defining a Class
A class is a special data type which defines
how to build a certain kind of object.
The class also stores some data items that
are shared by all the instances of this class
Instances are objects that are created which
follow the definition given inside of the class
Python doesn’t use separate class interface
definitions as in some languages
You just define the class and then use it
Methods in Classes
Define a method in a class by including
function definitions within the scope of the
class block
There must be a special first argument self
in all of method definitions which gets bound
to the calling instance
There is usually a special method called
__init__ in most classes
We’ll talk about both later…
A simple class def: student
class student:
“““A class representing a
student ”””
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
Creating and Deleting
Instances
Instantiating Objects
There is no “new” keyword as in Java.
Just use the class name with ( ) notation and
assign the result to a variable
__init__ serves as a constructor for the
class. Usually does some initialization work
The arguments passed to the class name are
given to its __init__() method
So, the __init__ method for student is passed
“Bob” and 21 and the new class instance is
bound to b:
b = student(“Bob”, 21)
Constructor: __init__
An __init__ method can take any number of
arguments.
Like other functions or methods, the
arguments can be defined with default values,
making them optional to the caller.
However, the first argument self in the
definition of __init__ is special…
Self
The first argument of every method is a
reference to the current instance of the class
By convention, we name this argument self
In __init__, self refers to the object
currently being created; so, in other class
methods, it refers to the instance whose
method was called
Similar to the keyword this in Java or C++
But Python uses self more often than Java
uses this
Self
Although you must specify self explicitly
when defining the method, you don’t include it
when calling the method.
Python passes it for you automatically
Defining a method: Calling a method:
(this code inside a class definition.)
def set_age(self, num): >>> x.set_age(23)
self.age = num
Deleting instances: No Need to “free”
When you are done with an object, you don’t
have to delete or free it explicitly.
Python has automatic garbage collection.
Python will automatically detect when all of the
references to a piece of memory have gone
out of scope. Automatically frees that
memory.
Generally works well, few memory leaks
There’s also no “destructor” method for
classes
Access to Attributes
and Methods
Definition of student
class student:
“““A class representing a student
”””
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
Traditional Syntax for Access
>>> f = student(“Bob Smith”, 23)
>>> f.full_name # Access attribute
“Bob Smith”
>>> f.get_age() # Access a method
23
Accessing unknown members
Problem: Occasionally the name of an attribute
or method of a class is only given at run time…
Solution:
getattr(object_instance, string)
string is a string which contains the name of
an attribute or method of a class
getattr(object_instance, string)
returns a reference to that attribute or method
getattr(object_instance, string)
>>> f = student(“Bob Smith”, 23)
>>> getattr(f, “full_name”)
“Bob Smith”
>>> getattr(f, “get_age”)
<method get_age of class
studentClass at 010B3C2>
>>> getattr(f, “get_age”)() # call it
23
>>> getattr(f, “get_birthday”)
# Raises AttributeError – No method!
hasattr(object_instance,string)
>>> f = student(“Bob Smith”, 23)
>>> hasattr(f, “full_name”)
True
>>> hasattr(f, “get_age”)
True
>>> hasattr(f, “get_birthday”)
False
Attributes
Two Kinds of Attributes
The non-method data stored by objects are
called attributes
Data attributes
• Variable owned by a particular instance of a class
• Each instance has its own value for it
• These are the most common kind of attribute
Class attributes
• Owned by the class as a whole
• All class instances share the same value for it
• Called “static” variables in some languages
• Good for (1) class-wide constants and (2)
building counter of how many instances of the
class have been made
Data Attributes
Data attributes are created and initialized by
an __init__() method.
• Simply assigning to a name creates the attribute
• Inside the class, refer to data attributes using self
—for example, self.full_name
class teacher:
“A class representing teachers.”
def __init__(self,n):
self.full_name = n
def print_name(self):
print self.full_name
Class Attributes
Because all instances of a class share one copy of a
class attribute, when any instance changes it, the value
is changed for all instances
Class attributes are defined within a class definition
and outside of any method
Since there is one of these attributes per class and not
one per instance, they’re accessed via a different
notation:
• Access class attributes using self.__class__.name notation
-- This is just one way to do this & the safest in general.
class sample: >>> a = sample()
x = 23 >>> a.increment()
def increment(self): >>> a.__class__.x
self.__class__.x += 1 24
Data vs. Class Attributes
class counter: >>> a = counter()
overall_total = 0 >>> b = counter()
# class attribute >>> a.increment()
def __init__(self): >>> b.increment()
self.my_total = 0 >>> b.increment()
# data attribute >>> a.my_total
def increment(self): 1
counter.overall_total = \ >>> a.__class__.overall_total
counter.overall_total + 1 3
self.my_total = \ >>> b.my_total
self.my_total + 1 2
>>> b.__class__.overall_total
3
Function Overloading
We generally don't need to overload functions in
Python. Python is dynamically typed, and supports
optional arguments to functions.
Read More: http://python-history.blogspot.in/2009/02/pythons-use-of-
dynamic-typing.html
Operator Overloading
This feature in Python, allows same operator to have
different meaning according to the context.
For example, the + operator can be used to, perform
arithmetic addition on two numbers, merge two lists
and concatenate two strings.
Example
A Final Example
Resources
https://docs.python.org/3/tutorial/classes.html
http://www.tutorialspoint.com/python/pdf/python_class
es_objects.pdf
http://www.programiz.com/python-programming/class
http://www.programiz.com/python-
programming/inheritance
Assignment
Write a menu driven banking program to
support the functionalities as shown below