Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Chapter 2

Class and Objects


Declaration
 These slides are made for UIT, BU students only. I am not
holding any copy write of it as I had collected these study
materials from different books and websites etc. I have not
mentioned those to avoid complexity.

8/25/2023 8:15 PM Dr. Dipankar Dutta, UIT, BU 1.2


Topics
 Class fundamentals
 Declaring objects
 Variables
 Methods
 Constructor
 Destructor
 Overloading
 Using objects as parameters
 Returning objects

8/25/2023 8:15 PM Dr. Dipankar Dutta, UIT, BU 1.3


Python
 Python is a multi-paradigm programming language, which
means it supports multiple programming paradigms, including:
 Object-Oriented Programming (OOP): Python is often
described as an object-oriented programming language. It
supports classes and objects, encapsulation, inheritance,
and polymorphism, which are fundamental principles of
object-oriented programming.
 Procedural Programming: Python also supports procedural
programming. You can write code in a procedural style,
using functions and procedures to organize and structure
your code.
 Functional Programming: While not purely functional,
Python has functional programming features. You can use
functions as first-class objects, create anonymous functions
(lambda functions), and use functions like map, filter, and
reduce for functional-style operations on lists and other data
structures.
8/25/2023 8:15 PM Dr. Dipankar Dutta, UIT, BU 1.4
Python Classes/Objects
 A Class is like an object constructor, or a "blueprint" for creating
objects. It is template of objects.
 Classes provide a means of bundling data and functionality
together.
 Creating a new class creates a new type of object, allowing new
instances of that type to be made.
 Each class instance or object can have attributes attached to it
for maintaining its state. Class instances can also have methods
(defined by their class) for modifying their state.

8/25/2023 8:15 PM Dr. Dipankar Dutta, UIT, BU 1.5


Python Classes/Objects
 Class creates a user-defined data structure, which holds its own
data members and member functions, which can be accessed
and used by creating an instance of that class.
 Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.6


Create a Class
 Example
Create a class named MyClass, with a property named x:
Code:
class MyClass:
x=5
print(MyClass)

You have to give “:” after the name of the class.

Output:
<class '__main__.MyClass'>

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.7


Python Classes/Objects
 The output <class '__main__.MyClass'> is a representation of a
Python class object. Let's break down its components:
 <class ...>: This part of the output indicates that you are dealing with
a class.
 '__main__': This is the name of the module where the class
MyClass is defined. In Python, when you run a script or program
directly (as opposed to importing it as a module), the module is
referred to as '__main__'. So, '__main__' indicates that MyClass is
defined in the main module, which is typically the module where
your script is being executed.
 MyClass: This is the name of the class itself. In this case, it's called
MyClass.
 So, in summary, <class '__main__.MyClass'> tells you that you
have a class named MyClass defined in the main module
('__main__'). This is often seen when you define classes and
objects directly in a Python script that you run.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.8


Class / Objects
 An Object is an instance of a Class. A class is like a blueprint
while an instance is a copy of the class with actual values.
 It‟s not an idea anymore, it‟s an actual dog, like a dog of breed
pug who‟s seven years old.
 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.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.9


Class / Objects

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.10


Declaring Objects (Also called
instantiating a class)
 When an object of a class is created, the class is said to be
instantiated. All the instances share the attributes and the
behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any
number of instances.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.11


Create Object
 Now we can use the class named MyClass to create objects:
 Example
Create an object named p1, and print the value of x:

Code:
p1 = MyClass()
print(p1.x)

Output:
5

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.12


The __init__() Function
 The examples above are classes and objects in their simplest
form, and are not really useful in real life applications.
 To understand the meaning of classes we have to understand
the built-in __init__() function.
 All classes have a function called __init__(), which is always
executed when the class is being initiated.
 Use the __init__() function to assign values to object properties,
or other operations that are necessary to do when the object is
being created.
 The __init__ method is similar to constructors in C++ and Java.
 The __init__() function is called automatically every time the
class is being used to create a new object.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.13


The __init__() Function
 Example:
 Create a class named Person, use the __init__() function to
assign values for name and age:
Code:
class Person:
#2 “_” at both sides of init
def __init__(self,name,age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
Output:
John
36

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.14


Types of constructors
 default constructor: The default constructor is a simple
constructor which doesn‟t accept any arguments. Its definition
has only one argument which is a reference to the instance being
constructed.
 parameterized constructor: constructor with parameters is
known as parameterized constructor. The parameterized
constructor takes its first argument as a reference to the instance
being constructed known as self and the rest of the arguments
are provided by the programmer.
 In Python, the self parameter in the __init__() method (and in
other instance methods) serves as a reference to the instance of
the class. It is a convention, and you can name it something else
if you want, but self is the widely accepted and recommended
name.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.15


Object Methods
 Objects can also contain methods. Methods in objects are
functions that belong to the object.
 Let us create a method in the Person class:
 Example
Code:
class Person:
#2 “_” at both sides of init
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
Output:
Hello my name is John
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.16
The self Parameter
 The self parameter is a reference to the current instance of the
class, and is used to access variables that belongs to the class.
 It does not have to be named self, you can call it whatever you
like, but it has to be the first parameter of any function in the
class:
 Example
Code:
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.17
Class and Instance Variables
 Instance variables are for data, unique to each instance and
 class variables are for attributes and methods shared by all
instances of the class.
 Instance variables are variables whose value is assigned inside
a constructor or method with self
 whereas class variables are variables whose value is assigned in
the class.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.18


Class and Instance Variables
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")

print('Rodger details:')
print('Rodger is a', Rodger.animal)

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.19


Class and Instance Variables
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)

print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)

# Class variables can be accessed using class


# name also
print("\nAccessing class variable using class name")
print(Dog.animal)

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.20


Class and Instance Variables
 Output:
Rodger details:
Rodger is a dog
Breed: Pug
Color: brown
Buzo details: Buzo is a dog
Breed: Bull dog
Color: black
Accessing class variable using class name
dog

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.21


Modify Object Properties
 You can modify properties on objects like this:
 Example
 Set the age of p1 to 40:
 Code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
 Output:
40
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.22
Delete Object Properties
 You can delete properties on objects by using the del keyword:
 Example
 Delete the age property from the p1 object:
 Code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1.age
print(p1.age)

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.23


Delete Object Properties
 Output:
Traceback (most recent call last):

File "demo_class7.py", line 13, in <module>

print(p1.age)

AttributeError: 'Person' object has no attribute 'age'

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.24


The pass Statement
 class definitions cannot be empty, but if you for some reason
have a class definition with no content, put in the pass statement
to avoid getting an error.
 Example:
class Person:

pass

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.25


Destructors
 Destructors are called when an object gets destroyed.
 In Python, destructors are not needed as much as in C++
because Python has a garbage collector that handles memory
management automatically.
 The __del__() method is a known as a destructor method in
Python. It is called when all references to the object have been
deleted i.e when an object is garbage collected.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.26


Destructors
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj

Output:
Employee created.
Destructor called, Employee deleted.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.27


Destructors
 The destructor was called after the program ended or when all
the references to object are deleted i.e. when the reference
count becomes zero, not when object went out of scope.
class Employee:

# Initializing
def __init__(self):
print('Employee created')

# Calling destructor
def __del__(self):
print("Destructor called")

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.28


Destructors
def Create_obj():
print('Making Object...')
obj = Employee()
print('function end...')
return obj

print('Calling Create_obj() function...')


obj = Create_obj()
print('Program End...')

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.29


Destructors
 Output:
Calling Create_obj() function...
Making Object...
Employee created
function end...
Program End...
Destructor called

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.30


Circular Reference
class Person:
def __init__(self, name):
self.name = name
self.friend = None # Initialize the friend attribute as None
# Create two Person objects
alice = Person("Alice")
bob = Person("Bob")
# Create a circular reference by making Alice and Bob friends
alice.friend = bob
bob.friend = alice

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.31


Circular Reference
 A circular reference in Python occurs when two or more objects
reference each other in a way that forms a loop. Circular
references can lead to memory leaks and issues with garbage
collection because Python's memory management relies on
reference counting and a cycle detector to reclaim memory when
objects are no longer reachable. Circular references prevent
objects from being properly deallocated because they are still
considered reachable from one another, even if they are no
longer needed.
 In this example, alice and bob are two Person objects, and they
have a friend attribute that can reference another Person object.
By setting alice.friend to bob and bob.friend to alice, we create a
circular reference. Both alice and bob are referencing each other,
forming a loop.
 Simply, it doesn‟t know the order in which to destroy the objects,
so it leaves them. Therefore, if your instances are involved in
circular references they will live in memory for as long as
the8:16application
8/25/2023 PM run. Dr. Dipankar Dutta, UIT, BU 1.32
Method Overloading
 Like other languages (for example, method overloading in C++)
do, python does not support method overloading by default. But
there are different ways to achieve method overloading in
Python.
 The problem with method overloading in Python is that we may
overload the methods but can only use the latest defined
method.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.33


Method Overloading
# First product method.
# Takes two argument and print their
# product
def product(a, b):
p=a*b
print(p)
# Second product method
# Takes three argument and print their
# product
def product(a, b, c):
p = a * b*c
print(p)
# Uncommenting the below line shows an error
# product(4, 5)
# This line will call the second product method
product(4, 5, 5)
Output:
100

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.34


Method Overloading
 Here „product‟ is not an instance method within a class; it's just a
regular function that takes two arguments, a and b. In Python,
you don't use „self‟ as the first argument in regular functions, only
in instance methods within classes.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.35


Method Overloading
# Function to take multiple arguments
def add(datatype, *args):

# if datatype is int
# initialize answer as 0
if datatype =='int':
answer = 0

# if datatype is str
# initialize answer as ''
if datatype =='str':
answer ='„”

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.36


Method Overloading
# Traverse through the arguments
for x in args:
# This will do addition if the
# arguments are int. Or concatenation
# if the arguments are str
answer = answer + x

print(answer)

# Integer
add('int', 5, 6)

# String
add('str', 'Hi ', 'Geeks')

Output:
11
Hi Geeks

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.37


Method Overloading
 In Python, *args is a special syntax used in function definitions to
allow you to pass a variable number of non-keyword (positional)
arguments to a function. The *args parameter allows you to pass
any number of arguments to the function as a tuple.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.38


Method Overloading
Method Overloading can be implemented by @dispatch. It is a
decorator available in external library like multipledispatch

from multipledispatch import dispatch

#passing two parameter


@dispatch(int,int)
def product(first,second):
result = first*second
print(result);

#passing three parameters


@dispatch(int,int,int)
def product(first,second,third):
result = first * second * third
print(result);

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.39


Method Overloading
#you can also pass data type of any value as per requirement
@dispatch(float,float,float)
def product(first,second,third):
result = first * second * third
print(result);
#calling product method with 2 arguments
product(2,3,2) #this will give output of 12
product(2.2,3.4,2.3) # this will give output of 17.985999999999997

Output:
12
17.985999999999997

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.40


Using objects as parameters
 In the example there are two classes Person and MyClass,
object of class Person is passed as parameter to the method of
class MyClass.

class MyClass():
def my_method(self, obj):
print('In my_method method of MyClass')
print("Name:", obj.name)
print("Age:", obj.age)

In MyClass there is one method my_method which takes one more


argument apart from self.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.41


Using objects as parameters
from MyClass import MyClass
class Person:
def __init__(self, name, age):
print(„__init__ called')
self.name = name
self.age = age
def display(self):
print('in display')
print("Name-", self.name)
print("Age-", self.age)
# object of class MyClass
obj = MyClass()
# passing person object to
# method of MyClass (self = person here)
obj.my_method(self)
person = Person('John', 40)
person.display()
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.42
Using objects as parameters
 In class Person, MyClass is also used so that is imported.
 In method display() object of MyClass is created.
 Then the my_method() method of class MyClass is called and
object of Person class is passed as parameter.
 On executing this Python program you get output as following.
__init__ called
in display
Name- John
Age- 40
In my_method method of MyClass
Name: John
Age: 40

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.43


Return statement
 The Python return statement is a key component
of functions and methods. You can use the return statement to
make your functions send Python objects back to the caller code.
These objects are known as the function‟s return value. You can
use them to perform further computation in your programs.
 In general, a function takes arguments (if any), performs some
operations, and returns a value (or object).
 To write a Python function, you need a header that starts with
the def keyword, followed by the name of the function, an
optional list of comma-separated arguments inside a required
pair of parentheses, and a final colon.
 The second component of a function is its code block, or body.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.44


Return statement
 The Python return statement is a special statement that you
can use inside a function or method to send the function‟s result
back to the caller. A return statement consists of
the return keyword followed by an optional return value.
 The return value of a Python function can be any Python object.
Everything in Python is an object. So, your functions can return
numeric values (int, float, and complex values), collections and
sequences of objects (list , tuple, dictionary, or set objects), user-
defined objects, classes, functions, and even modules or
packages.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.45


Explicit return Statements
 An explicit return statement immediately terminates a function
execution and sends the return value back to the caller code.
def return_42():
...
return 42 # An explicit return statement
 If you define a function with an explicit return statement that has
an explicit return value, then you can use that return value in any
expression:
num = return_42()
num
 Note that you can use a return statement only inside a function
or method definition. If you use it anywhere else, then you‟ll get
a SyntaxError:
return 42
Output:
File "<stdin>", line 1
SyntaxError:
8/25/2023 8:16 PM 'return' outside function
Dr. Dipankar Dutta, UIT, BU 1.46
Explicit return Statements
 You can use any Python object as a return value. Since
everything in Python is an object, you can return strings, lists,
tuples, dictionaries, functions, classes, instances, user-defined
objects, and even modules or packages.
def get_even(numbers):
even_nums = [num for num in numbers if not num % 2]
return even_nums
get_even([1, 2, 3, 4, 5, 6])
Output:
[2, 4, 6]
 Here's a breakdown of the code:
 [...]: This square bracket syntax is used to create a new list.
 num for num in numbers: This part of the list comprehension is a loop that
iterates over each element num in the numbers list.
 if not num % 2: This is a conditional statement that checks if num is even. The %
operator calculates the remainder when num is divided by 2. If there's no
remainder (i.e., num % 2 is 0), then the number is even.
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.47
Explicit return Statements
 If num is an even number (e.g., 2, 4, 6), then num % 2 will
evaluate to 0, and in Python, 0 is considered equivalent to False.
 If num is an odd number (e.g., 1, 3, 5), then num % 2 will
evaluate to a non-zero value, and in Python, non-zero values are
considered equivalent to True.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.48


Implicit return Statements
 A Python function will always have a return value. There is no
notion of procedure or routine in Python which does not return
any value. So, if you don‟t explicitly use a return value in
a return statement, or if you totally omit the return statement,
then Python will implicitly return a default value for you. That
default return value will always be None.
 Say you‟re writing a function that adds 1 to a number x, but you
forget to supply a return statement. In this case, you‟ll get
an implicit return statement that uses None as a return value:

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.49


Implicit return Statements
def add_one(x):
# No return statement at all
result = x + 1

value = add_one(5)
print(value)

Output:
None

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.50


Returning vs Printing
def print_greeting():
print("Hello, World")
print_greeting()
Hello, World

def return_greeting():
return "Hello, World“
return_greeting()
'Hello, World„

 Both functions seem to do the same thing. In both cases, you


see Hello, World printed on your screen. There‟s only a subtle
visible difference - the single quotation marks in the second
example.
 There‟s no visible difference for int type.

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.51


Returning Multiple Values
 You can use a return statement to return multiple values from a
function. To do that, you just need to supply several return
values separated by commas.
import statistics as st
def describe(sample):
return st.mean(sample), st.median(sample), st.mode(sample)
 Once you‟ve coded describe(), you can take advantage of a
powerful Python feature known as iterable unpacking to unpack
the three measures into three separated variables, or you can
just store everything in one variable:
sample = [10, 2, 4, 7, 9, 3, 9, 8, 6, 7]
mean, median, mode = describe(sample)
mean
6.5
median
7.0
mode 7
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.52
Returning Multiple Named-Objects
 When you‟re writing a function that returns multiple values in a
single return statement, you can consider using
a collections.namedtuple object to make your functions more
readable. namedtuple is a collection class that returns a subclass
of tuple that has fields or attributes. You can access those
attributes using dot notation or an indexing operation.
 The initializer of namedtuple takes several arguments. However,
to start using namedtuple in your code, you just need to know
about the first two:
 typename holds the name of the tuple-like class that you‟re
creating. It needs to be a string.
 field_names holds the names of the fields or attributes of the tuple-
like class. It can be a sequence of strings such as ["x", "y"] or a
single string with each name separated by whitespace or commas,
such as "x y" or "x, y".

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.53


Returning Multiple Named-Objects
import statistics as st
from collections import namedtuple

def describe(sample):
Desc = namedtuple("Desc", ["mean", "median", "mode"])
return Desc(
st.mean(sample),
st.median(sample),
st.mode(sample),
)

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.54


Returning Multiple Named-Objects
sample = [10, 2, 4, 7, 9, 3, 9, 8, 6, 7]
stat_desc = describe(sample)

stat_desc
Desc(mean=5.7, median=6.0, mode=6)

# Get the mean by its attribute name


stat_desc.mean
5.7

# Get the median by its index


stat_desc[1]
6.0

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.55


Returning Multiple Named-Objects
# Unpack the values into three variables
mean, median, mode = describe(sample)

mean
5.7

mode
6

8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.56


End of Chapter 2

Questions?

You might also like