You are on page 1of 9

CLASSES AND OBJECTS IN

PYTHON
CLASSES

• A class is a blueprint for creating objects (instances). It defines


the attributes and methods that objects of the class will have.
Classes are defined using the 'class' keyword followed by the
class name. Variables defined within a class are called attributes.
They represent the state of the object. Functions defined within
a class are called methods. They represent the behavior of the
object.
• Classes encapsulate data (attributes) and methods (functions)
that operate on that data into a single unit.
EXAMPLE CLASS

• class Car:
• def __init__(self, brand, model):
• self.brand = brand
• self.model = model

• def drive(self):
• return f"{self.brand} {self.model} is driving"
• Constructor Method (__init__): This method is called when an instance of the class is created. It initializes the
object's attributes.
• Instance Attributes: These are variables that belong to each instance of the class. They are accessed using self.
• Instance Methods: These are functions defined inside the class. They can access and modify instance attributes.
OBJECTS

• An object is an instance of a class. It is created using the class as a


template.
• To create an object, you instantiate the class by calling its
constructor method (usually __init__) with appropriate arguments.
• Objects have attributes that are specific to each instance. These
attributes hold the state of the object.
• Objects can invoke methods defined in their class. These methods
operate on the object's attributes.
EXAMPLE OBJECT CREATED USING
THE CLASS CAR

• car1 = Car("Toyota", "Camry")


• print(car1.brand) # Output: Toyota
• print(car1.drive()) # Output: Toyota Camry is driving
TREE NODE CLASS IN PYTHON

• class TreeNode:
• def __init__(self, value):
• self.value = value
• self.children = []

• def add_child(self, child_node):


• self.children.append(child_node)
CREATING A TREE AND ADDING ITS
NODES USING THE TREE CLASS

• root = TreeNode("A")
• child1 = TreeNode("B") A
• child2 = TreeNode("C") / \
• child3 = TreeNode("D") B C
\
• root.add_child(child1) D
• root.add_child(child2)
• child2.add_child(child3)
BINARY TREE NODE CLASS IN PYTHON

• class BinaryTreeNode:
• def __init__(self, value):
• self.value = value
• self.left = None
• self.right = None
CREATING A BINARY TREE AND
ADDING ITS NODES USING THE TREE
CLASS
• # Create nodes
• root = BinaryTreeNode("A")
• node1 = BinaryTreeNode(“B") A
• node2 = BinaryTreeNode(“C") / \
• Node3 = BinaryTreeNode(“D") B C
• # Build the binary tree structure /
• root.left = node1 D
• root.right = node2
• root.left.left = node3

You might also like