5-6

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Object Oriented

Programming
Dr. Bharat Singh
PhD, CSE
Contents
• Accessing Class Members
• Class Attribute
• Class Method
• Defining Funtion in class
• Destructor
• Self argument
Write a Python program to create a Vehicle class
with max_speed and mileage instance attributes.

class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage

modelX = Vehicle(240, 18)


print(modelX.max_speed, modelX.mileage)
Exercise: Write the code for the
given class and object
Exercise: Write the code
import mathfor the

given class and objectdefself.radius=radius


class Circle:
__init__(self, radius=1):

def getPerimeter(self):
return 2*self.radius*math.pi
def getArea(self):
return math.pi*self.radius*self.radius
def setradius(self, radius):
self.radius=radius

c1=Circle() #create default circle with radius=1


print("the area of the circle of radius ", c1.radius,
"is" ,c1.getArea())

c2=Circle(5)
print("the area of the circle of radius ",c2.radius, "
is" ,c2.getArea())

c3=Circle(25)

c4=Circle(125)
Write a Python program to create a calculator class.
Include methods for basic arithmetic operations.
# Define a class called Calculator to
perform basic arithmetic operations
class Calculator:
# Define a method for addition that
takes two arguments and returns their
sum
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y !=0:
return x / y
else:
return("Cannot divide by zero.")

calculator = Calculator()
result = calculator.add(7,5)
print("the sum of 7 + 5 =", result)
Example class Car():
# init method or constructor
def __init__(self, model, color):
self.model = model
self.color = color

def show(self):
print("Model is", self.model )
print("color is", self.color )

# both objects have different self which contain their attributes


audi = Car("audi a4", "blue")
ferrari = Car("ferrari 488", "green")

audi.show() # same output as car.show(audi)


ferrari.show() # same output as car.show(ferrari)

print("Model for audi is ",audi.model)


print("Colour for ferrari is ",ferrari.color)
__init__() method
• The __init__ method is class GFG:
def __init__(self, name, company):
similar to constructors in C++ self.name = name
and Java. self.company = company

• Constructors are used to def __str__(self):


initializing the object’s state. return f"My name is {self.name} and I work in {self.company}."

• It runs as soon as an object of my_obj = GFG("John", "Hindustan Fertilizers")


print(my_obj)
a class is instantiated.
• The method is useful to do
any initialization you want to
do with your object.
__str__() method
• Python has a particular method class GFG:
called __str__(). def __init__(self, name, company):
self.name = name
self.company = company
• It is used to define how a class object def __str__(self):
should be represented as a string. return f"My name is {self.name} and I work in {self.company}."

• When a class object is used to create my_obj = GFG("John", "GeeksForGeeks")


a string using the built-in functions print(my_obj)
print() and str(), the __str__()
function is automatically used.
Class Attributes
• When we design a class, we use instance variables and class variables.

• In Class, attributes can be defined into two parts:

• Instance variables: The instance variables are attributes attached to an


instance of a class. We define instance variables in the constructor ( the
__init__() method of a class).

• Class Variables: A class variable is a variable that is declared inside of


class, but outside of any instance method or __init__() method.
Class Attributes

• Objects do not share instance attributes.


Instead, every object has its copy of the
instance attribute and is unique to each
object.
• All instances of a class share the class
variables. However, unlike instance
variables, the value of a class variable is not
varied from object to object.
• Only one copy of the static variable will be
created and shared between all objects of
the class.
Accessing properties and assigning
values

• An instance attribute can be accessed or modified by using the dot


notation:

instance_name.attribute_name.
• A class variable is accessed or modified using the class name
class Student:
# class variables
school_name = 'ABC School'

# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age

s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)

# access class variable


print('School name:', Student.school_name)

# Modify instance variables


s1.name = 'Jessa'
s1.age = 14
print('Student:', s1.name, s1.age)

# Modify class variables


Student.school_name = 'XYZ School'
print('School name:', Student.school_name)
Class Methods
• Inside a Class, we can define the following three types of methods.
• Instant Method, Class Method and static method

• Instance method: Used to access or modify the object state. If we use


instance variables inside a method, such methods are called instance
methods.
• Any method we create in a class will automatically be created as an
instance method unless we explicitly tell Python that it is a class or
static method.
Class Methods
• Class method: Used to access or modify the class state. In method
implementation, if we use only class variables, then such type of
methods we should declare as a class method. A class method is
bound to the class and not the object of the class. It can access only
class variables.
• Static method: It is a general utility method that performs a task in
isolation. Inside this method, we don’t use instance or class variable
because this static method doesn’t have access to the class attributes.
Class Methods
# class methods demo
class Student:
# class variable
school_name = 'ABC School'
Define and call an instance
method and class method
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age s1 = Student("Harry", 12)
# instance method # call instance methods
def show(self): s1.show()
# access instance variables and class variables s1.change_age(14)
print('Student:', self.name, self.age, Student.school_name)
# instance method # call class method
def change_age(self, new_age): Student.modify_school_name('XYZ School')
# modify instance variable # call instance methods
self.age = new_age s1.show()
# class method
@classmethod
def modify_school_name(cls, new_name):
# modify class variable
cls.school_name = new_name
Modify Object Properties
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color

def show(self):
print("Fruit is", self.name, "and Color is", self.color)

# creating object of the class


obj = Fruit("Apple", "red")

# Modifying Object Properties


obj.name = "strawberry"

# calling the instance method using the object obj


obj.show()
# Output Fruit is strawberry and Color is red
Delete object properties
class Fruit:
def __init__(self, name, color):
• We can delete the self.name = name
object property by self.color = color

using the del keyword. def show(self):


After deleting it, if we print("Fruit is", self.name, "and Color is", self.color)
try to access it, we will # creating object of the class
get an error. obj = Fruit("Apple", "red")

# Deleting Object Properties


del obj.name

# Accessing object properties after deleting


print(obj.name)
# Output: AttributeError: 'Fruit' object has no attribute 'name'
Delete Objects
class Employee:
depatment = "IT"
• we can also delete the object
by using a del keyword. An def show(self):
print("Department is ", self.depatment)
object can be anything like,
class object, list, tuple, set, emp = Employee()
etc. emp.show()

# delete object
del emp

# Accessing after delete object


emp.show()
# Output : NameError: name 'emp' is not defined
Constructor With Default Values
class Student:
# constructor with default values age and classroom
• Python allows us to define a def __init__(self, name, age=12, classroom=7):
constructor with default values. self.name = name
self.age = age
The default value will be used if self.classroom = classroom
we do not pass arguments to the
# display Student
constructor at the time of object def show(self):
creation. print(self.name, self.age, self.classroom)

# creating object of the Student class


emma = Student('Emma')
emma.show()

kelly = Student('Kelly', 13)


Emma 12 7 kelly.show()
Kelly 13 7
Destructor
• Destructor is a special method that is called when an object gets
destroyed.
• Destructor is used to perform the clean-up activity before destroying
the object, such as closing database connections or filehandle.
• Python has a garbage collector that handles memory management
automatically. For example, it cleans up the memory when an object
goes out of scope.
• We must release or close the other resources object were using, such
as open files, database connections, cleaning up the buffer or cache.
To perform all those cleanup tasks we use destructor
Destructor
Destructor
• The destructor is the reverse of the constructor.
• The constructor is used to initialize objects, while the destructor is
used to delete or destroy the object that releases the resource
occupied by the object.
• In Python, destructor is not called manually but completely
automatic. destructor gets called in the following two cases
• When an object goes out of scope or
• The reference counter of the object reaches 0.

• The special method __del__() is used to define a destructor.


class Student:

# constructor
def __init__(self, name):
print('Inside Constructor')
self.name = name
print('Object initialized')

def show(self):
print('Hello, my name is', self.name)

# destructor
def __del__(self):
print('Inside destructor')
print('Object destroyed')

# create object
s1 = Student('Emma')
s1.show()

# delete object
del s1
Important Points to Remember
about Destructor
• The __del__ method is called for
class Vehicle:
any object when the reference def __init__(self, speed):
count for that object becomes zero. self.speed = speed;
• The reference count for that object def __del__(self):
becomes zero when the application print('Release resources')
ends, or we delete all references
# creating an object
manually using the del keyword. car = Vehicle(350);
• The destructor will not invoke when
# to delete the object explicitly
we delete object reference. It will del car
only invoke when all references to
the objects get deleted.
The self Parameter Python
• The class contains instance variables and methods. class GFG:
def __init__(self, name, company):
• Whenever we define instance methods for a class,
self.name = name
we use self as the first parameter, but it is not used self.company = company
when the method is called.
• self is a parameter that references the object itself. def show(self):
print("Hello my name is " + self.name+" and I" +
• Using self, we can access the instance variable and " work in "+self.company+".")
instance method of the object.

obj = GFG("John", "GeeksForGeeks")


• The first argument self refers to the current object. obj.show()
• self in Python is equivalent to this in C++ or Java.
The self Parameter Python
class Student:
# constructor
def __init__(self, name, age):
• Whenever we call an instance self.name = name
self.age = age
method through an object, the
Python compiler implicitly # self points to the current object
def show(self):
passes object reference as the # access instance variable using self
first argument commonly print(self.name, self.age)
known as self.
# creating first object
emma = Student('Emma', 12)
emma.show()

# creating Second object


kelly = Student('Kelly', 13)
kelly.show()
• It is not mandatory to name class GFG:
def __init__(somename, name, company):
the first parameter as a self. somename.name = name
We can give any name somename.company = company
whatever we like, but it has to def show(somename):
be the first parameter of an print("Hello my name is " + somename.name +
instance method. " and I work in "+somename.company+".")

obj = GFG("John", "GeeksForGeeks")


obj.show()
Constructor Overloading
class Student:
# one argument constructor
• Constructor overloading is a concept of def __init__(self, name):
having more than one constructor with a print("One arguments constructor")
different parameters list in such a way so that self.name = name
each constructor can perform different tasks.
• For example, we can create a three # two argument constructor
constructor which accepts a different set of def __init__(self, name, age):
parameters print("Two arguments constructor")
self.name = name
self.age = age
• Python does not support constructor
overloading.
# creating first object
• If we define multiple constructors then, the emma = Student('Emma')
interpreter will considers only the last
constructor and throws an error if the # creating Second object
sequence of the arguments doesn’t match as kelly = Student('Kelly', 13)
per the last constructor.
Constructor Overloading
• while Python does not support class Person:
traditional method and def __init__(self, name, age=None):
constructor overloading. self.name = name
self.age = age
• You can leverage default values
and variable-length argument # Example Usage
lists to achieve similar person1 = Person(‘Alice’)
person2 = Person(’Bob ’, 25)
functionality.
# Output
print(person1.name, person1.age)
print(person2.name, person2.age)
Method overloading
• Two or more methods have the
same name but different
numbers of parameters or
different types of parameters, or
both. These methods are called
overloaded methods and this is
called method overloading.
Method overloadingclass MathOperations:
def add(self, a, b=None, c=None):
if b is not None and c is not None:
• while Python does not support return a + b + c
elif b is not None:
traditional method and constructor return a + b
overloading. else:
• You can leverage default values and return a
variable-length argument lists to
achieve similar functionality. # Example Usage
math_obj = MathOperations()
• In this example, the MathOperations result1 = math_obj.add(5)
class defines an add method with result2 = math_obj.add(5, 10)
optional parameters b and c, result3 = math_obj.add(5, 10, 15)
allowing for method overloading
# Output
based on the number of arguments. print(result1)
print(result2)
print(result3)

You might also like