0% found this document useful (0 votes)
6 views20 pages

Python Objects and Classes Explained

The document provides an overview of Python's object-oriented programming, explaining the concepts of classes and objects, including how to define them and access their attributes. It covers constructors, including default, parameterized, and non-parameterized constructors, as well as destructors and their usage in memory management. Examples are provided to illustrate the creation and manipulation of classes and objects in Python.

Uploaded by

Upasana Bhardwaj
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)
6 views20 pages

Python Objects and Classes Explained

The document provides an overview of Python's object-oriented programming, explaining the concepts of classes and objects, including how to define them and access their attributes. It covers constructors, including default, parameterized, and non-parameterized constructors, as well as destructors and their usage in memory management. Examples are provided to illustrate the creation and manipulation of classes and objects in Python.

Uploaded by

Upasana Bhardwaj
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

Python Objects and Classes

• Python is a versatile programming language that supports various


programming styles, including object-oriented programming (OOP)
through the use of objects and classes.
An object is any entity that has attributes and behaviors. For example, a
parrot is an object. It has

• attributes - name, age, color, etc.


• behavior - dancing, singing, etc.
• Similarly, a class is a blueprint for that object.
Python Class and Object

• Python 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 class.
• Define Python Class
• We use the class keyword to create a class in Python. For example,
class ClassName:
# class definition
Let's see an example,
class Bike:
name = ""
gear = 0

Here,

Bike - the name of the class


name/gear - variables inside the class with default values "" and 0 respectively.
Note: The variables inside a class are called attributes.
Python 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.

Here's the syntax to create an object.


• objectName = ClassName()
Let's see an example,
# create class
class Bike:
name = ""
gear = 0

# create objects of class


bike1 = Bike()
Here, bike1 is the object of the class. Now, we can use this object to access the class attributes.
Access Class Attributes Using
Objects
• We use the . notation to access the attributes of a class. For example

# modify the name attribute


• [Link] = "Mountain Bike"
# access the gear attribute
[Link] the attributes of a class.

Here, we have used [Link] and [Link] to change and access


the value of name and gear attribute respectively.
Example 1: Python Class and
Objects
# define a class
class Bike:
name = ""
gear = 0

# create object of class


bike1 = Bike()

# access attributes and assign new values


[Link] = 11
[Link] = "Mountain Bike"

print(f"Name: {[Link]}, Gears: {[Link]} “)


Output

Name: Mountain Bike, Gears: 11


Constructors in Python

• In python every class has a constructor, it is a special method specified inside


a class. The constructor/initializer will automatically invoke while creating a
new object for the class. When an object is initialized, the constructor assigns
values to the data members within the class.
• It is not necessary to define a constructor explicitly. But for creating a
constructor we need to follow the below rules −
• For a class, it allows only one constructor.
• The constructor name must be __init__.
• A constructor must be defined with an instance attribute (nothing but
specifying the self keyword as a first parameter).
• It cannot return any value, except None.
• Syntax
class A():
def __init__(self):
pass
Example
class SampleClass():
def __init__(self):
print("it a sample class constructor")
Output
it a sample class constructor
# creating an object of the class
class faculty: class faculty:
def putdata(self): #method1 def __init__(self): #method1
[Link]=int(input("inter faculty id")) [Link]=int(input("inter faculty id"))
[Link]=input("enter name)") [Link]=input("enter name)")
[Link]=float(input("enter faculty
[Link]=float(input("enter faculty salary"))
salary"))
def display(self): #method2
def display(self): #method2
print("faculty id", [Link])
print("faculty id", [Link])
print("faculty name", [Link])
print("faculty name", [Link])
print("facult salary", [Link])
print("facult salary", [Link])
a=faculty()
a=faculty() [Link]()
[Link]() b=faculty()
[Link]() [Link]()
• In the above code, object A is created for the SampleClass() and for
this instance, the method __init__(self) is automatically executed. So
that it has displayed the statement from the contructor.

• Constructors are three types.


• Default constructor
• Parameterized Constructor
• Non-Parameterized Constructor
• Default Constructor
Default constructors are not defined by the user, Python itself creates a constructor
during the compilation of the program. It doesn’t perform any task but initializes the
objects.

• Parameterized Constructor
The parameterized constructor, takes one or more arguments along with self. It is
useful when you want to create an object with custom values for its attributes. The
parameterized constructor allows us to specify the values of the object’s attributes
when the object is created.
• Example
• Let’s see an example of a class with a parameterized constructor
Parameterised Constructor
class faculty:
def __init__(self,a,b,c): #method1
[Link]=a
[Link]=b
[Link]=c
def display(self): #method2
print("faculty id", [Link])
print("faculty name", [Link])
print("facult salary", [Link])
a=faculty(1,"meena",1200)
[Link]()
class Family:
members = 10
def __init__(self, count):
[Link] = count

def disply(self):
print("Number of members is", [Link])

joy_family = Family(25)
joy_family.disply()
Output
Number of members is
25
• Rather than using the default members attribute value 10, here the
object joy family is created with the custom value 25. And this value
can be utilized for this instance as it is assigned to the [Link]
attribute.

• Non-Parameterized Constructor
The non-parameterized constructors don’t take any arguments other
than self. It is useful when you want to manipulate the values of the
instance attributes.
Let’s see an example for non-parameterized constructors.
player1 = Player()
class Player: print('player1 results')
def __init__(self): [Link](2)
[Link]()
[Link] = 0

print('p2 results')
# Add a move() method with steps parameter p2 = Player()
[Link]()
def move(self, steps):
[Link] = steps Output
print([Link]) player1 results
2
def result(self): 2
p2 results
print([Link])
0
• The player1 object is manipulated the “position” attribute by using
the move() method. And the p2 object is accessed the default value of
the “position” attribute.
Destructors in Python
• The users call Destructor for destroying the object. In Python, developers might not
need destructors as much it is needed in the C++ language. This is because Python has
a garbage collector whose function is handling memory management automatically.

• we will discuss how the destructors in Python works and when the users can use them.
• The __del__() function is used as the destructor function in Python. The user can call
the __del__() function when all the references of the object have been deleted, and it
becomes garbage collected.

• Syntax:
def __del__(self):
# the body of destructor will be written here.
In the following example, we will use the __del__() function
and the del keyword for deleting all the references of the
object so that the destructor will involve automatically.

# we will illustrate destructor function in Python program


# we will create Class named Animals
class Animals:

# we will initialize the class


def __init__(self):
print('The class called Animals is CREATED.')

# now, we will Call the destructor


def __del__(self):
print('The destructor is called for deleting the Animals.') Output:

The class called Animals is CREATED.


object = Animals() The destructor is called for deleting the Animals.
del object
• Explanation -
In the above code, the destructor has called when the references to the
object are deleted or after the program was ended. This means that the
reference count for the object becomes zero and not when the object
goes out of scope. We will explain this by showing the next example.
We can also notice that the destructor is called after the ending of the program.
# We will create Class named Animals
class Animals:

# Initialize the class


def __init__(self):
print('The class called Animals is CREATED.')

# now, we will Call the destructor


def __del__(self):
print('The destructor is called for deleting the Animals.')

def Create_object(): Output:


print('we are creating the object')
we are calling the Create_object() function now
object = Animals()
we are creating the object
print('we are ending the function here') The class called Animals is CREATED.
return object we are ending the function here
The Program is ending here
print('we are calling the Create_object() function now') The destructor is called for deleting the Animals.
object = Create_object()

You might also like