Lesson 02 - Constructors & Destructors
Lesson 02 - Constructors & Destructors
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()
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.
aPerson = Person()
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)
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
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))
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.
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")
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