Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Python Modul 5 - Sivanandha m s

Uploaded by

shi20012023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python Modul 5 - Sivanandha m s

Uploaded by

shi20012023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Modul 5

CLASSES and OBJECTS


Classes/Objects
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and methods.
• A Class is like an object constructor, or a "blueprint" for creating objects.
• An object represents an entity in the real world with its identity and
behaviour.Create a Class
• To create a class, use the keyword class
#Create a class named MyClass, with a property named x:
class MyClass:
x = 5Create Object
• Now we can use the class named MyClass to create objects:
• You access the object's attributes using the dot operator with object
#Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)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:Constructor
• Constructor is the special function that is automatically executed when an object of a class is created.
• In Python, there is a special function called “init” which act as a Constructor.
• It must begin and end with double underscore.
• This function will act as an ordinary function; but only difference is, it is executed automatically when the
object is created.
• This constructor function can be defined with or without arguments.
• This method is used to initialize the class variables.
Example
#Create a class named Person, use the __init__() function to assign
values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
• The __init__() function is called automatically every time the class is being used to create a new object.
• __init__() also called class constructor or initialization method
• Self parameter is a reference to the current instance of the class, and is used to access variables that belong
to the class.
Object Methods
• Objects can also contain methods. Methods in objects are functions that belong to the class.
• You declare other class methods like normal functions with the exception that the first argument to each
method is self.
• Python adds the self argument to the list for you; you do not need to include it when you call the methods.
Example
• #Insert a function that prints a greeting, and execute it on the p1 object:
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.myfunc()
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:
Modify Object Properties
• You can modify properties on objects like this:
p1.age = 40
Delete Object Properties
• You can delete properties on objects by using the del keyword
del p1.age
Delete Objects
• You can delete objects by using the del keyword
del p1
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.
class Person:
pass
Sameness
• To find out if two references refer to the same object, use the is operator
P1=Point()
P1.x=3
P1.y=4
P2=Point()
P2.x=3
P2.y=4
P1 is P2 => False

• If we assign P1 to P2, then the two variables are aliases of the same object
• P2=P1
• P1 is P2 => True
• This type of equality is called shallow equality because it compares only the references, not the contents of
the objects
• To compare the contents of the objects –deep equality
def samePoint(p1,p2):
return (p1.x==p2.x) and (p1.y==p2.y)
samePoint(p1,p2)=>True
If the two variables refer to the same object,they have both shallow and deep equality
Copying
• Copying an object is often an alternative to aliasing
• Copy module contains a function called copy that can duplicate any object
>>>import copy
>>>p1=Point()
>>>p1.x=3
>>>p1.y=4
>>>p2=copy.copy(p1)
>>>p1==p2
False
>>>samePoint(p1,p2)True

• Once we import the copy module, we can use the copy method to make a new Point. P1 and p2 are not the
same point, but they contain the same data
• To copy a simple object like a Point, which doesnot contain any embedded objects, copy is sufficient. This
is called shallow copying
• The copy module contains a method named deepcopy that copies not only the object but also any
embedded objects.This operation is called a deep copy
>>>b2=copy.deepcopy(b1)
Now b1 and b2 are completely separate objects

Destructor
• Destructors are called when an object gets destroyed.
• In Python, destructors are not needed as much needed 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.
• Note : A reference to objects is also deleted when the object goes out of reference or when the program
ends.
Syntax of destructor declaration
def __del__(self):
# body of destructor
Destructor Example
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj
print(“Program ENd”)
Output
Employee created
Destructor called, Employee deleted.
Program End
Destructor Example
• The destructor was called after the program ended or when all the references to object are deleted
class Employee:
# Initializing
def __init__(self):
print('Employee created')
# Calling destructor
def __del__(self):
print("Destructor called")
obj=Employee()
print(“Program End..”)
Output
Employee created
Program End..
Destructor called
Inheritance
• Inheritance allows us to define a class that inherits all the methods and properties from another class.
• Parent class is the class being inherited from, also called base class.
• Child class is the class that inherits from another class, also called derived class.
Create a parent class
• Any class can be a parent class, so the syntax is the same as creating any other class:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
Create a child class
• To create a class that inherits the functionality from another class, send the parent class as a parameter
when creating the child class:
class Student(Person):
pass
• Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
• Now the Student class has the same properties and methods as the Person class.
x = Student("Mike", "Olsen")
x.printname()
Add the __init__() Function
• So far we have created a child class that inherits the properties and methods from its parent.
• We want to add the __init__() function to the child class (instead of the pass keyword).
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
• When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.
• Note: The child's __init__() function overrides the inheritance of the parent's __init__() function.
• To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Use super() function
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
• By using the super() function, you do not have to use the name of the parent element, it will automatically
inherit the methods and properties from its parent.
Add Properties
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

x = Student("Mike", "Olsen", 2019)


Add Methods
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)

Obj=Student(“John”,”Mathew”,2020)
Obj.welcome()
• If you add a method in the child class with the same name as a function in the parent class, the inheritance
of the parent method will be overridden

You might also like