Agenda
• Classes
• Object
• Instantiating a class
• Access Class Attributes Using Objects
• Create Multiple Objects of Class
• Constructors
Classes
• A class is considered as a blueprint of objects. We can think of the class as
a sketch (prototype) of a house. It contains all the details about the floors,
doors, windows, etc. Based on these descriptions we build the house.
House is the object.
• 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.
• Is an object oriented programming language.
• Almost everything is an object, with its properties and methods.
Classes
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.)
operator. Eg.: My class.Myattribute
Create a Class
Example:
class MyClass:
x=5
class Bike:
name = ""
gear = 0
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.
• 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.
Objects
• An object is called an instance of a class. For example, suppose Bike is a
class then we can create objects like bike1, bike2, etc from the class.
• Syntax:
objectName = ClassName()
Create Object
Example:
# create class
class Bike:
name = ""
gear = 0
# create objects of class
bike1 = Bike()
instantiating a class
• When an object of a class is created, the class is said to be instantiated.
• 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.
Example
Access Class Attributes Using Objects
• We use the . notation to access the attributes of a class.
Example:
# create class
class Bike:
name = ""
gear = 0
# create objects of class
bike1 = Bike()
# access the gear attribute
bike1.gear
# modify the name attribute
bike1.name = "Mountain Bike"
Example
# create class
class Bike:
name = ""
gear = 0
# create objects of class
bike1 = Bike()
# access the gear attribute
bike1.gear
# modify the name attribute
bike1.name = "Mountain Bike“
# access attributes and assign new values
bike1.gear = 11
print(f"Name: {bike1.name}, Gears: {bike1.gear} ")
Create Multiple Objects of Class
Example:
# define a class
class Employee:
# define an attribute
employee_id = 0
# create two objects of the Employee class
employee1 = Employee()
employee2 = Employee()
# access attributes using employee1
employee1.employee_id = 1001
print(f"Employee ID: {employee1.employee_id}")
# access attributes using employee2
employee2.employee_id = 1002
print(f"Employee ID: {employee2.employee_id}")
Constructors
• Earlier we assigned a default value to a class attribute:
Example:
class Bike:
name = "“
# create object
bike1 = Bike()
bike1.name
• However, we can also initialize values using the constructors.
Example:
class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
bike1 = Bike()
Constructor
• __init__() is the constructor function that is called whenever a new object
of that class is instantiated.
• The constructor above initializes the value of the name attribute. We have
used the self.name to refer to the name attribute of the bike1 object.
• If we use a constructor to initialize values inside a class, we need to pass
the corresponding value during the object creation of the class.
• bike1 = Bike("Mountain Bike")
The __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:
• 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)
Example
# Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
The __str__() Function
• The __str__() function controls what should be returned when the class
object is represented as a string.
• If the __str__() function is not set, the string representation of the object
is returned:
• Example
• The string representation of an object WITHOUT the __str__() function:
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
_str_()
• That is used to define how a class object should be represented as a
string. It is often used to give an object a human-readable textual
representation, which is helpful for logging, debugging, or showing users
object information. When a class object is used to create a string using the
built-in functions print() and str(), the __str__() function is automatically
used. You can alter how objects of a class are represented in strings by
defining the __str__() method.
Example
class GFG:
def __init__(self, name, company):
self.name = name
self.company = company
def __str__(self):
return f"My name is {self.name} and I work in {self.company}."
my_obj = GFG("John", "GeeksForGeeks")
print(my_obj)
Example
• The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Object Methods
• Objects can also contain methods. Methods in objects are functions that belong to
the object.
• Let us create a method in the Person class:
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:
Example
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Example
class GFG:
def __init__(self, name, company):
self.name = name
self.company = company
def show(self):
print("Hello my name is " + self.name+" and I" +
" work in "+self.company+".")
obj = GFG("John", "GeeksForGeeks")
obj.show()
Example
The Self Parameter does not call it to be Self, You can use any other name instead of it.
Here we change the self to the word someone and the output will be the same.
class GFG:
def __init__(somename, name, company):
somename.name = name
somename.company = company
def show(somename):
print("Hello my name is " + somename.name +
" and I work in "+somename.company+".")
obj = GFG("John", "GeeksForGeeks")
obj.show()
Methods
• We can also define a function inside a Python class.
• A Function defined inside a class is called a method.
Example:
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", self.length * self.breadth)
# create object of Room class
study_room = Room()
# assign values to all the attributes
study_room.length = 42.5
study_room.breadth = 30.8
# access method inside class
study_room.calculate_area()
Delete Object Properties
• You can delete properties on objects by using the del keyword:
Example
• Delete the age property from the p1 object:
• del p1.age
Delete Objects
• You can delete objects by using the del keyword:
Example
• Delete the p1 object:
• 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.
Example
class Person:
pass
Example
# Class for Dog
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
Example - Continution
# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
# Class variables can be accessed using class
# name also
print("\nAccessing class variable using class name")
print(Dog.animal)
Example
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed):
# Instance Variable
self.breed = breed
# Adds an instance variable
def setColor(self, color):
self.color = color
Example - Continuation
# Retrieves instance variable
def getColor(self):
return self.color
# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())