0% found this document useful (0 votes)
13 views40 pages

Lesson 02 - Constructors & Destructors

Uploaded by

dohaminta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views40 pages

Lesson 02 - Constructors & Destructors

Uploaded by

dohaminta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Constructors & Destructors

What Is The ‘Self’ Parameter


• Reminder: When defining/calling methods of a
class there is always at least one parameter.
• This parameter is called the ‘self’ reference which
allows an object to access attributes inside its
def sayName():
methods. print "My name is...",
name
• ‘Self’ needed to distinguish the attributes of
different objects of the same class.
• Example: Whose name is
bart = Person() this? (This won’
lisa = Person() work)
lisa.sayName()
The Self Parameter: A Complete Example
• Name of the online example: person2.py
class Person:
name = "I have no name :("
def sayName(self):
print("My name is...", self.name)

def main():
lisa = Person()
lisa.name = "Lisa Simpson, pleased to meet you."
bart = Person()
bart.name = "I'm Bart Simpson, who the hek are you???!!!"

lisa.sayName()
bart.sayName()

main()

“The Simpsons”  Fox


Recap: Accessing Attributes & Methods
• Inside the class definition (inside the body of the class
methods)
– Preface the attribute or method using the ‘self’ reference
class Person:
name = "No-name"
def sayName(self):
print("My name is...", self.name)

• Outside the class definition


– Preface the attribute or method using the name of the
reference used when creating the object.
def main():
lisa = Person()
bart = Person()
lisa.name = "Lisa Simpson, pleased to meet you."
Constructor?
• Creating and initializing objects of a given class is a
fundamental step in object-oriented programming.
• This step is often referred to as object
construction or instantiation.
• The tool responsible for running this instantiation
process is commonly known as a class constructor.
• Every class has a constructor, but it is not required
to explicitly define it.
Defining Class Methods: Full Example
class Person:
name = ""
def sayName(self):
print("My name is...", self.name)

def main():
aPerson = Person()
aPerson.sayName()
aPerson.name = "Big Smiley :D"
aPerson.sayName()

main()
Defining Class Methods: Full Example
• Name of the online example: person1.py
class Person:
name = "I have no name :("
def sayName(self):
print("My name is...", self.name)

def main():
aPerson = Person()
aPerson.sayName()
aPerson.name = "Big Smiley :D"
aPerson.sayName()

main()
Class Constructors
• Constructors are generally used for
instantiating an object of a class.

• The main objective of the constructors is to


assign values to the data members of a class
when an object of the class is created.
Class Constructors
• Constructors are always called when an object
is created and is simulated by the __init__()
method.
• It accepts the self-keyword, which refers to
itself (the object), as a first argument which
allows accessing the attributes or method of
the class.
Initializing The Attributes Of A Class
• Classes have a special method that can be used to initialize
the starting values of a class to some specific values.
No spaces here
• This method is automatically called whenever an object is
created.
• Format:
class <Class name>:
This design
def __init__(self, <other parameters>):
<body of the method>
approach is
consistent with
• Example: many
class Person:
languages
name = ""
def __init__(self):
self.name = "No name"
Constructor: A Special Method
• Constructor method: a special method that is used
when defining a class and it is automatically called
when an object of that class has been created.
– E.g., aPerson = Person() # This calls the constructor

• In Python this method is named ‘init’.


• Other languages may require a different name for
the syntax but it serves the same purpose (initializing
the fields of an object as it’s being created).
• This method should never have a return statement
that returns a value.
Objects Employ References
Assign the address
of the object into
the reference

aPerson = Person()

Creates the Calls the constructor


reference and creates an object
variable
Types of Constructors
• Non-parameterized
• Parameterized
Non-parameterized Constructor
• The non-parameterized constructor uses when
we do not want to manipulate the value or the
constructor that has only self as an argument.
• Its definition has only one argument which is a
reference to the instance being constructed.
Non-parameterized Constructor
class Student:
# no-argument constructor
def __init__(self):
self.section = "A"
self.session =2023

def display(self):
print ("Section is:", self.section, "Session is:", self.session)
# Creating object of the class
stud = Student()
stud.display()
Parameterized Constructor
• The parameterized constructor has multiple
parameters along with the self.
• It 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.
Parameterized Constructor
class Student:
# Parameterized constructor
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no

def display(self):
print ("Roll No.: “,self.roll_no,”Name :”, self.name)

# Creating object of the class


stud1 = Student("Navya", 34)
stud2 = Student("Mia", 67)

stud1.display()
stud2.display()
Checks on default values
class Rectangle:
def __init__(self, width, height):
if not (isinstance(width, (int, float)) and width > 0):
raise ValueError(f"positive width expected, got {width}")
self.width = width
if not (isinstance(height, (int, float)) and height > 0):
raise ValueError(f"positive height expected, got {height}")
self.height = height

rectangle = Rectangle(-21, 42)


More than One Constructor

class Student:
# Default Constructor

def __init__(self):
print("First constructor call")
# Parameterized constructor
def __init__(self, n, r):
print("Second constructor call\n")
self.name = n
self.roll_no = r
def display(self):
print ("Roll No.: %d \nName: %s" % (self.roll_no, self.name))

# Creating object of the class


stud1 = Student("Navya", 34)
stud2 = Student("Mia", 67)

stud1.display()
stud2.display()
Objects Employ References (2)
• Objects are accessed through a reference.
• The reference and the object are two separate
memory locations.
class Person:
def __init__(self,newAge,newName):
self.age = newAge
self.name = newName

def displayAge(aPerson):
print("%s age %d" %(aPerson.name,aPerson.age))
Objects Employ References (3)
def start():
person1 = Address = 1000
Person(13,"Person2") person2 @=1000 Age: 13
person2 = person1 Name: Person2
displayAge(person1) @=1000
person1
displayAge(person2)
print()

start()
Objects Employ References (2)
def start():
person1 = Address = 1000
Person(13,"Person2") person2 @=1000 Age: 13
person2 = person1 Name: Person2
displayAge(person1) @=1000
@=2000
person1
displayAge(person2)
print() Address = 2000
Age: 888
person1 = Name: Person1
Person(888,"Person1")
displayAge(person1)
displayAge(person2)

start()
Default Parameters
• Similar to other methods, ‘init’ can be defined so that if
parameters aren’t passed into them then default values can
be assigned.
• Example:
def __init__ (self, name = "I have no name"):
This method can be called
either when a personalized
name is given or if the name
is left out.

• Method calls (to ‘init’), both will work


smiley = Person()
jt = Person("James")
Default Parameters: Full Example
• Name of the online example: init_method2.py
class Person:
def __init__(self, name = "I have no name"):
self.name = name

def main():
smiley = Person()
print("My name is...", smiley.name)
jt = Person("James")
print("My name is...", jt.name)

main()
Default Parameters: Another Example
class MyClass:
def __init__(self, name=None):
if name is None:
print("Default value set")
else:
self.name = name
print("Passed value set with name: ", self.name)

def method(self):
if hasattr(self, 'name'):
print("Method called with name", self.name)
else:
print("Method called without a name")

# Create an object of the class using the default constructor


obj1 = MyClass()

# Call a method of the class


obj1.method()

# Create an object of the class using the parameterized constructor


obj2 = MyClass("John")

# Call a method of the class


obj2.method()
Advantages of Constructors
• Initialization of objects
• Easy to implement
• Better Readability
• Encapsulation
Disadvantages of Constructor
• Overloading not supported
• Limited functionality
• Constructors may be unnecessary
Overall Remarks
Constructors in Python can be useful for
initializing objects and enforcing encapsulation.
However, they may not always be necessary and
are limited in their functionality compared to
constructors in other programming languages.
Destructor
• Destructors are called when an object gets
destroyed.
• It’s the polar opposite of the constructor,
which gets called on creation.
• These methods are only called after object
creation to destroy them. They are not called
manually but completely automatic.
Destructor
• A destructor is a function called automatically
when an object is deleted or destroyed.

• An object is destroyed by calling:


del obj
Destructor
• In Python, destructors are not needed as
much as in C++ because Python has a garbage
collector that handles memory management
automatically.
Destructor
• Take into mind that destroying an object
with del is optional, you can create objects
and never delete them. They are then only
deleted when the program closes. However,
this can eat up a lot of memory in large
programs.
Destructor
• A destructor has this format:
def __del__(self):

• It is always part of a class, even if not defined.
(If not defined, Python assumes an empty
destructor).
Destructor : Example
class Vehicle:
def __init__(self):
print('Vehicle created.')
def __del__(self):
print('Destructor called, vehicle deleted.')
car = Vehicle() # this is where the object is created
and the constructor is called
del car # this is where the destructor function gets
called
Note
• 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.
Destructor : Example
# Python program to illustrate destructor

class Employee:

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

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

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

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


obj = Create_obj()
print('Program End...')
Write an output for this program
Output
Calling Create_obj() function...
Making Object...
Employee created
function end...
Program End...
Destructor called
Note
• A reference to objects is also deleted when
the object goes out of reference or when the
program ends.
Class Task
• Modify the room class to calculate area by
using constructors and destructors.

You might also like