0% found this document useful (0 votes)
16 views8 pages

Object Oriented

The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, methods, inheritance and encapsulation. It provides examples of creating classes and objects, using methods, and inheriting from parent classes.

Uploaded by

J Jam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views8 pages

Object Oriented

The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, methods, inheritance and encapsulation. It provides examples of creating classes and objects, using methods, and inheriting from parent classes.

Uploaded by

J Jam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

Chapter 8.

Object Oriented

⊙ Python has been an object-oriented language.


– Creating and using classes and objects are downright easy.

Object Oriented Programming (OOP)


⊙ Python is a multi-paradigm programming language. It supports
different programming approaches.
⊙ One of the popular approaches to solve a programming problem is
by creating objects. This is known as OOP.
⊙ An object has two characteristics:
– attributes – behavior
⊙ Let’s take an example:
A parrot is can be an object,as it has the following properties:
– Attributes: name, age, color
– Behavior: singing, dancing
⊙ The concept of OOP in Python focuses on creating reusable code.
This concept is also known as DRY (Don’t Repeat Yourself).

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 (class variables and instance
variables) and methods, accessed via dot notation.
⊙ 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

V. Vinoharan University of Jaffna


84 Chapter 8. Object Oriented

class’s methods.
⊙ Data member: A class variable or instance variable that holds
data associated with a class and its objects.
⊙ Function overloading: The assignment of more than one behavior
to a particular function.
– The operation performed varies by the types of objects or argu-
ments involved.
⊙ Instance variable: A variable that is defined inside a method and
belongs only to the current instance of a class.
⊙ Inheritance: The transfer of the characteristics of a class to other
classes that are derived from it.
⊙ 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.
⊙ 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 is defined by
its class.
– An object comprises both data members (class variables and
instance variables) and methods.
⊙ Operator overloading: The assignment of more than one function
to a particular operator.

Class
⊙ The class statement creates a new class definition. The name of the
class immediately follows the keyword class followed by a colon.
⊙ The first string inside the class is called docstring and has a brief
description about the class. Although not mandatory, this is highly
recommended.

class ClassName:
'docstring: Optional class documentation string'
class_suite

⊙ A class parrot contains all the details about parrot. Here, a parrot
is an object.

V. Vinoharan University of Jaffna


85

⊙ The example for class of parrot can be:


class Parrot:
pass

Constructors
⊙ Class functions that begin with double underscore __ are called
special functions as they have special meaning.
⊙ Of one particular interest is the __init__() function. This special
function gets called whenever a new object of that class is instanti-
ated.
⊙ You declare other class methods like normal functions with the
exception that the first argument to each method is self.
– Python adds the self argument to the list for you; you do not
need to include it when you call the methods.
⊙ Following table lists some generic functionality that you can override
in your own classes
– __init__(self [,args...]): Constructor.
Sample Call: obj = className(args)
– __del__(self): Destructor, deletes an object.
Sample Call: del obj
– __repr__(self): Evaluable string representation.
Sample Call: repr(obj)
– __str__(self): Printable string representation.
Sample Call: str(obj)
– __cmp__(self, x): Object comparison.
Sample Call: cmp(obj, x)

Object
⊙ An object (instance) is an instantiation of a class.
– When class is defined, only the description for the object is
defined.
– Therefore, no memory or storage is allocated.
⊙ The example for object of parrot class can be:
obj = Parrot()

⊙ Here, obj is an object of class Parrot.

V. Vinoharan University of Jaffna


86 Chapter 8. Object Oriented

⊙ Example

class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age

# instantiate the Parrot class


blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

Output:
Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old

⊙ Instead of using the normal statements to access attributes, you can


use the following functions
– The getattr(obj, name[, default]): to access the attribute
of object.
– The hasattr(obj,name): to check if an attribute exists or not.
– The setattr(obj,name,value): to set an attribute. If at-
tribute does not exist, then it would be created.
– The delattr(obj, name): to delete an attribute.

hasattr(blu, 'age') # Returns true if 'age' attribute exists


getattr(blu, 'age') # Returns value of 'age' attribute
setattr(blu, 'age', 8) # Set attribute 'age' at 8
delattr(blu, 'age') # Delete attribute 'age'

V. Vinoharan University of Jaffna


87

Methods
⊙ Methods are functions defined inside the body of a class.
– They are used to define the behaviors of an object.
⊙ Example
class Parrot:
def __init__(self, name, age): # instance attributes
self.name = name
self.age = age
def sing(self, song): # instance method
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)

# instantiate the object


blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())

Output:
Blu sings 'Happy'
Blu is now dancing

Built-In Class Attributes


⊙ Every Python class keeps the following built-in attributes and they
can be accessed using dot operator like any other attribute
– __dict__: Dictionary containing the class’s namespace.
– __doc__: Class documentation string or none, if undefined.
– __name__: Class name.
– __module__: Module name in which the class is defined. This
attribute is “__main__” in interactive mode.
– __bases__: A possibly empty tuple containing the base classes,
in the order of their occurrence in the base class list.

Inheritance
⊙ Inheritance is a way of creating a new class for using details of an
existing class without modifying it.

V. Vinoharan University of Jaffna


88 Chapter 8. Object Oriented

⊙ The newly formed class is a derived class (or child class). Similarly,
the existing class is a base class (or parent class).
⊙ Example
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")

# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")

peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()

Output:
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
⊙ Similar way, you can drive a class from multiple parent classes as
follows
class A: # define your class A
.....

V. Vinoharan University of Jaffna


89

class B: # define your class B


.....

class C(A, B): # subclass of A and B


.....

– You can use issubclass() or isinstance() functions to check a rela-


tionships of two classes and instances.
– The issubclass(sub, sup) boolean function returns true if the given
subclass sub is indeed a subclass of the superclass sup.
– The isinstance(obj, Class) boolean function returns true if obj is
an instance of class Class or is an instance of a subclass of Class

Encapsulation
⊙ In OOP, we can restrict access to methods and variables.
– This prevents data from direct modification which is called en-
capsulation.
– We denote private attributes using underscore as the prefix i.e
single _ or double __.
⊙ Example

class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price

c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()

Output:

V. Vinoharan University of Jaffna


90 Chapter 8. Object Oriented

Selling Price: 900


Selling Price: 900
Selling Price: 1000

Polymorphism
⊙ Polymorphism is an ability to use a common interface for multiple
forms.
– Suppose, we need to color a shape, there are multiple shape
options (rectangle, square, circle).
– However we could use the same method to color any shape.
– This concept is called Polymorphism.
⊙ Example

class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")

class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")

# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)

Output:
Parrot can fly
Penguin can't fly

V. Vinoharan University of Jaffna

You might also like