0% found this document useful (0 votes)
3 views10 pages

Python Unit - 5

python advanced version of unit 5

Uploaded by

jan
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)
3 views10 pages

Python Unit - 5

python advanced version of unit 5

Uploaded by

jan
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

Unit – 5

Object Oriented Programming

Python is a multi-paradigm programming language. It supports different programming


approaches. In Python, object-oriented Programming (OOPs) is a programming paradigm that
uses objects and classes in programming. It aims to implement real-world entities like
inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of
OOPs is to bind the data and the functions that work on that together as a single unit so that
no other part of the code can access this data.

Main Concepts of Object-Oriented Programming (OOPs)


• Class
• Objects
• Polymorphism
• Encapsulation
• Inheritance

One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).

An object has two characteristics:

• attributes

• behavior
Let's take an example:

A parrot is an object, as it has the following properties:

• name, age, color as attributes

• singing, dancing as behavior

Class
A class is a blueprint for the object. A class is a collection of objects. A class contains the
blueprints or the prototype from which the objects are being created. It is a logical
entity that contains some attributes and methods.
To understand the need for creating a class let’s consider an example, let’s say you wanted to
track the number of dogs that may have different attributes like breed, age. If a list is used, the
first element could be the dog’s breed while the second element could represent its a ge. Let’s
suppose there are 100 different dogs, then how would you know which element is supposed
to be which? What if you wanted to add other properties to these dogs? This lacks
organization and it’s the exact need for classes.
Some points on Python class:
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator.
Eg.: [Link]

Class Definition Syntax:


class ClassName:
# Statement-1
.
.
.
# Statement-N

We can think of class as a sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here, a
parrot is an object.
The example for class of parrot can be :

class Parrot:

pass

Here, we use the class keyword to define an empty class Parrot . From class, we construct
instances. An instance is a specific object created from a particular class.
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 .

Suppose we have details of parrots. Now, we are going to show how to build the class and
objects of parrots.

Example 1: Creating Class and Object in Python

class Parrot:

# class attribute
species = "bird"

# instance attribute
def __init__(self, name, age):
[Link] = name
[Link] = 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( [Link], [Link]))
print("{} is {} years old".format( [Link], [Link]))

Output

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

In the above program, we created a class with the name Parrot . Then, we define attributes.
The attributes are a characteristic of an object.
These attributes are defined inside the __init__ method of the class. It is the initializer
method that is first run as soon as the object is created.
Then, we create instances of the Parrot class. Here, blu and woo are references (value) to
our new objects.
We can access the class attribute using __class__.species . Class attributes are the same for
all instances of a class. Similarly, we access the instance attributes
using [Link] and [Link] . However, instance attributes are different for every instance of a
class.

Classes vs Instances
Classes are used to create user-defined data structures. Classes define functions
called methods, which identify the behaviors and actions that an object created from the
class can perform with its data.

In this tutorial, you’ll create a Dog class that stores some information about the
characteristics and behaviors that an individual dog can have.

A class is a blueprint for how something should be defined. It doesn’t actually contain any
data. The Dog class specifies that a name and an age are necessary for defining a dog, but it
doesn’t contain the name or age of any specific dog.

While the class is the blueprint, an instance is an object that is built from a class and
contains real data. An instance of the Dog class is not a blueprint anymore. It’s an actual dog
with a name, like Miles, who’s four years old.

Put another way, a class is like a form or questionnaire. An instance is like a form that has
been filled out with information. Just like many people can fill out the same form with their
own unique information, many instances can be created from a single class.
Instance Methods
Instance methods are functions that are defined inside a class and can only be
called from an instance of that class. Just like .__init__(), an instance method’s first
parameter is always self.

Open a new editor window in IDLE and type in the following Dog class:

class Dog:
species = "Canis familiaris"

def __init__(self, name, age):


[Link] = name
[Link] = age

# Instance method
def description(self):
return f"{[Link]} is {[Link]} years old"

# Another instance method


def speak(self, sound):
return f"{[Link]} says {sound}"
This Dog class has two instance methods:

1. .description() returns a string displaying the name and age of the dog.
2. .speak() has one parameter called sound and returns a string containing the dog’s
name and the sound the dog makes.

Save the modified Dog class to a file called [Link] and press F5 to run the program. Then
open the interactive window and type the following to see your instance methods in action:

>>>

>>> miles = Dog("Miles", 4)

>>> [Link]()
'Miles is 4 years old'

>>> [Link]("Woof Woof")


'Miles says Woof Woof'

>>> [Link]("Bow Wow")


'Miles says Bow Wow'
In the above Dog class, .description() returns a string containing information about
the Dog instance miles. When writing your own classes, it’s a good idea to have a method
that returns a string containing useful information about an instance of the class.
However, .description() isn’t the most Pythonic way of doing this.

When you create a list object, you can use print() to display a string that looks like the list:

>>>

>>> names = ["Fletcher", "David", "Dan"]


>>> print(names)
['Fletcher', 'David', 'Dan']
Let’s see what happens when you print() the miles object:

>>>

>>> print(miles)
<__main__.Dog object at 0x00aeff70>
When you print(miles), you get a cryptic looking message telling you that miles is
a Dog object at the memory address 0x00aeff70. This message isn’t very helpful. You can
change what gets printed by defining a special instance method called .__str__().

In the editor window, change the name of the Dog class’s .description() method
to .__str__():

class Dog:
# Leave other parts of Dog class as-is

# Replace .description() with __str__()


def __str__(self):
return f"{[Link]} is {[Link]} years old"
Save the file and press F5 . Now, when you print(miles), you get a much friendlier output:

>>>

>>> miles = Dog("Miles", 4)


>>> print(miles)
'Miles is 4 years old'
Methods like .__init__() and .__str__() are called dunder methods because they begin
and end with double underscores. There are many dunder methods that you can use to
customize classes in Python. Although too advanced a topic for a beginning Python book,
understanding dunder methods is an important part of mastering object-oriented
programming in Python.

Objects
The object is an entity that has a state and behavior associated with it. It may be any
real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point
numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or
any single string is an object. The number 12 is an object, the string “Hello, world” is an
object, a list is an object that can hold other objects, and so on. You’ve been using objects all
along and may not even realize it.
An object consists of :
• State: It is represented by the attributes of an object. It also reflects the properties of an
object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
• Identity: It gives a unique name to an object and enables one object to interact with other
objects.
To understand the state, behavior, and identity let us take the example of the class dog
(explained above).
• The identity can be considered as the name of the dog.
• State or Attributes can be considered as the breed, age, or color of the dog.
• The behavior can be considered as to whether the dog is eating or sleeping.

Example: Creating an object

obj = Dog()

This will create an object named obj of the class Dog defined above. Before diving deep into
objects and class let us understand some basic keywords that will we used while working with
objects and classes.

Example 1: Creating a class and object with class and instance attributes

class Dog:
# class attribute

attr1 = "mammal"

# Instance attribute

def __init__(self, name):

[Link] = name

# Driver code

# Object instantiation

Rodger = Dog("Rodger")

Tommy = Dog("Tommy")

# Accessing class attributes

print("Rodger is a {}".format(Rodger.__class__.attr1))

print("Tommy is also a {}".format(Tommy.__class__.attr1))

# Accessing instance attributes

print("My name is {}".format([Link]))

print("My name is {}".format([Link]))

Output

Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
Example 2: Creating Class and objects with methods

class Dog:

# class attribute

attr1 = "mammal"

# Instance attribute

def __init__(self, name):

[Link] = name

def speak(self):

print("My name is {}".format([Link]))

# Driver code

# Object instantiation

Rodger = Dog("Rodger")

Tommy = Dog("Tommy")

# Accessing class methods

[Link]()

[Link]()

Output

My name is Rodger
My name is Tommy

Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
Example : Creating Methods in Python

class Parrot:

# instance attributes
def __init__(self, name, age):
[Link] = name
[Link] = age

# instance method
def sing(self, song):
return "{} sings {}".format([Link], song)

def dance(self):
return "{} is now dancing".format([Link])

# instantiate the object


blu = Parrot("Blu", 10)

# call our instance methods


print([Link]("'Happy'"))
print([Link]())

Output

Blu sings 'Happy'


Blu is now dancing

In the above program, we define two methods i.e sing() and dance() . These are called
instance methods because they are called on an instance object i.e blu .
The self
1. Class methods must have an extra first parameter in the method definition. We do not give
a value for this parameter when we call the method, Python provides it
2. If we have a method that takes no arguments, then we still have to have one argument.
3. This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as [Link](arg1, arg2), this is automatically
converted by Python into [Link](myobject, arg1, arg2) – this is all the special self is
about.
The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object
of a class is instantiated. The method is useful to do any initialization you want to do with your
object.
Now let us define a class and create some objects using the self and __init__ method.

You might also like