0% found this document useful (0 votes)
11 views

Lesson8-Python.Classes.and.Objects_9c2fcd217994e06ed8bb27b97828a2bc

Python classes

Uploaded by

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

Lesson8-Python.Classes.and.Objects_9c2fcd217994e06ed8bb27b97828a2bc

Python classes

Uploaded by

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

Python Classes

and Objects
CSCN02C – Object-Oriented
Programming
Objectives
● Classes and Objects
○ Defining classes and objects and their implementation on Python
● Default Parameters and Methods
○ Defining how to initialize default parameters, constructors, desctructors and string representation
of a class
● Class and Instance Variables
○ Defining how to instantiate a class using different methods
Classes and Objects
Python Classes and Objects Part 1
What is a Class?
● A class is a user-defined blueprint or prototype from
which objects are created. 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 can have attributes attached to it for
maintaining its state.
● Class instances can also have methods (defined by their
class) for modifying their state.
What is a Class?

SEDAN SUV COUPE

CROSSOVER HATCHBACK

CONVERTIBLE MINIVAN

SPORTS CAR STATION WAGON


What is a Class?
Car Class: Year | Type | Wheel | Door

Ford BMW iX3 Honda City Toyota Toyota


Mustang Full-Electric i-VTEC Yaris 2000GT
2023 2023 2009 hatchback 1968
… … … 2007 …

What is a Class?
● The class creates a user-defined data
structure, which holds its own data members
and member functions, which can be accessed class Class_Name:
and used by creating an instance of that class. #statement
● A class is like a blueprint for an object.
● Some points on Python class:
#main class
● Classes are created by keyword class.
● Attributes are the variables that
obj = Class_Name()
print(obj.attr)
belong to a class.
● Attributes are always public and can
be accessed using the dot (.) operator.
Eg.: My class.Myattribute
What is a Class?
● CREATING A PYTHON CLASS

class Car:
def __init__(self, car_type, chassis, engine):
self.car_type = car_type
self.chassis = chassis
self.engine = engine

def cardata(self):
print(“Chassis/Engine:”,
self.chassis, self.engine)
print(“Car Type:”, self.car_type)
What is an Object?
● 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 car,
like a car of Toyota which is made in 2021.
● You can have many cars to create many
different instances, but without the class as
a guide, you would be lost, not knowing
what information is required.
What is an Object?
● 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.
What is an Object?
Toyota
States/Attributes
Chassis
Engine
DECLARING CLASS OBJECTS Wheelbase …
(also known as instantiating a class) Behavior
● When an object of a class is created, Speed
Gas Type
the class is said to be instantiated. Fuel Economy ….
● 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.
Toyota Vios Toyota Wigo Toyota
Fortuner
What is an Object?
DECLARING CLASS OBJECTS
(also known as instantiating a class)

class Car: #main class


def __init__(self, car_type, chassis, engine): ToyotaCamry = Car(“sedan”,
self.car_type = car_type “unibody”, “XLE”)
self.chassis = chassis print(ToyotaCamry.chassis)
ToyotaCamry.cardata()
self.engine = engine

def cardata(self): OUTPUT


print(“Chassis/Engine:”,
self.chassis, self.engine) unibody
print(“Car Type:”, self.car_type) Chassis/Engine: unibody XLE
Car Type: Sedan
Default Parameters
and Methods
Python Classes and Objects Part 2
Self Parameter
● When we call a method of this object as
class Car:
pyobject.method(arg1, arg2), this is
automatically converted by Python into def __init__(self, car_type, engine):
PyClass.method(myobject, arg1, arg2) – self.car_type = car_type
self.engine = engine
this is all the special self is about.
def cardata(self):
print(“Engine:”, self.engine)
print(“Car Type:”, self.car_type)

ToyotaCamry = Car(“sedan”, “XLE”)


print(ToyotaCamry.chassis)
ToyotaCamry.cardata()
Self Parameter
● The Self Parameter does not require for
class Car:
you to name it “self”. You can use any
other name instead of it. def __init__(cats, car_type, engine):
● Here we change the self to the word cats cats.car_type = car_type
cats.engine = engine
and the output will be the same.
def cardata(cats):
print(“Engine:”, cats.engine)
print(“Car Type:”, cats.car_type)

ToyotaCamry = Car(“sedan”, “XLE”)


print(ToyotaCamry.chassis)
ToyotaCamry.cardata()
Pass Parameter
● The program’s execution is unaffected
by the pass statement’s inaction.
● It merely permits the program to skip
past that section of the code without
class MyClass:
doing anything. pass
● It is frequently employed when the
syntactic constraints of Python
demand a valid statement but no
useful code must be executed.
_ _init_ _() method
● The __init__ method is similar to
constructors in C++ and Java. class Car:

Constructors are used to initializing the def __init__(self, car_type, engine):


object’s state. self.car_type = car_type
● Like methods, a constructor also contains a self.engine = engine

collection of statements(i.e. instructions) that def cardata(self):


are executed at the time of Object creation. print(“Engine:”, self.engine)
● It runs as soon as an object of a class is print(“Car Type:”, self.car_type)

instantiated.
● The method is useful to do any initialization ToyotaCamry = Car(“sedan”, “XLE”)
print(ToyotaCamry.chassis)
you want to do with your object. ToyotaCamry.cardata()
_ _del_ _() method
● The __del__ method is known as destructor, class Car:
which are called when an object gets
def __init__(self):
destroyed. print(“Car object created”)
● In Python, destructors are not needed as
much as in C++ because Python has a def __del__(self):
print(“Car object destroyed”);
garbage collector that handles memory
management automatically.
● It is called when all references to the object ToyotaCamry = Car()
del ToyotaCamry
have been deleted i.e when an object is
OUTPUT
garbage collected.
Car object created
Car object destroyed
_ _del_ _() method
● The destructor was called after the program class Car:
ended or when all the references to object are
def __init__(self):
deleted, i.e when the reference count print(“Car object created”)
becomes zero, not when object went out of
scope. def __del__(self):
print(“Car object destroyed”);

ToyotaCamry = Car()
del ToyotaCamry
OUTPUT

Car object created


Car object destroyed
_ _del_ _() method
class Car: OUTPUT

def __init__(self): Making Object...


print(“Car object created”) Car object created
function end...
def __del__(self): program end...
print(“Car object destroyed”); Car object destroyed

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

ToyotaCamry = Create_obj()
print(“program end...”);
_ _del_ _() method
Advantages of using destructors in Python:
● Automatic cleanup: Destructors provide automatic cleanup of resources used by an
object when it is no longer needed. This can be especially useful in cases where
resources are limited, or where failure to clean up can lead to memory leaks or other
issues.
● Consistent behavior: Destructors ensure that an object is properly cleaned up,
regardless of how it is used or when it is destroyed. This helps to ensure consistent
behavior and can help to prevent bugs and other issues.
● Easy to use: Destructors are easy to implement in Python and can be defined using the
__del__() method.
_ _del_ _() method
Advantages of using destructors in Python:
● Supports object-oriented programming: Destructors are an important feature of
object-oriented programming and can be used to enforce encapsulation and other
principles of object-oriented design.
● Helps with debugging: Destructors can be useful for debugging, as they can be used
to trace the lifecycle of an object and determine when it is being destroyed.
_ _str_ _() method
● The __str__ method is used to define how a class Car:
class object should be represented as a def __init__(self, name, engine):
self.name = name
string. self.engine = engine
● It is often used to give an object a human-
readable textual representation, which is def __str__(self):
return f”This is a {self.name}
helpful for logging, debugging, or showing and its engine is {self.engine}”
users object information.
● When a class object is used to create a string
ToyotaCamry = Car(“Camry”, “XLE”)
using the built-in functions print() and str(), print(ToyotaCamry)
the __str__() function is automatically used.
● You can alter how objects of a class are OUTPUT
represented in strings by defining the This is a Camry and its engine is XLE
__str__() method.
Class and
Instance Variables
Python Classes and Objects Part 3
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.
● We can define instance variables within 2 ways:
● Using a constructor
● Using Getters and Setters (normal way)
Instance Variables
Using a constructor

class Car:
brand = “Toyota”
def __init__(self, car_type, engine):
self.car_type = car_type
OUTPUT
self.engine = engine
Camry Details:
Camry = Car(“sedan”, “XLE”)
Camry is made by Toyota
Yaris = Car(“compact”, “Dual-VVT”
Car Type: sedan
Engine: XLE
print(“Camry Details:”)
print(“Camry is made by”, Camry.brand)
print(“Car Type:”, Camry.car_type)
print(“Engine:”, Camry.engine)
Instance Variables
Using Getters and Setters (normal way)
class Car: Yaris = Car(“Hatchback”)
brand = “Toyota” Yaris.setEngine(“Dual-VVT”)
def __init__(self, car_type): Yaris.setChassis(“unibody”)
self.car_type = car_type
print(“Yaris Details:”)
def setEngine(self, engine) print(Yaris.getChassis())
self.engine = engine print(Yaris.getEngine())

def setChassis(self, chassis)


self.chassis = chassis
OUTPUT
def getEngine(self)
Yaris Details:
return self.engine
unibody
Dual-VVT
def getChassis(self)
return self.chassis

You might also like