Python Classes and Objects

Python tutorial · PySpark.in

Python Classes and Objects

Object-Oriented Programming in Python starts with two key components: Classes and Objects.
Understanding these concepts is essential for writing clean, modular, and reusable code.

What is a Class?

A class is a blueprint or template used to create objects.
It defines:

Think of a class as a design plan, and objects as the actual items created from that plan.

Syntax of a Class

```

hider
class ClassName:
    # class attribute
    attribute_name = value
    # method
    def method_name(self):
        # method body
        Pass

```

What is an Object?

An object is an instance of a class.
When you create an object:

Each object can have different values for its attributes but shares the same structure.

Example: Creating a Class and Object

```
# Defining a class
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll

    def display(self):
        print(f"Name: {self.name}, Roll: {self.roll}")

# Creating objects of the class
student1 = Student("Sahil", 101)
student2 = Student("Ravi", 102)

# Accessing methods
student1.display()
student2.display()
```

Understanding the Example

1. class Student:

Defines a new class named Student.

2. __init__() – Constructor

Automatically runs when a new object is created.
It initializes object attributes.

3. self keyword

Refers to the current object.
Used inside the class to access attributes and methods.

4. Objects:

```
hide
student1 = Student("Sahil", 101)
student2 = Student("Ravi", 102)

```

These are two separate instances of the Student class.

5. Calling Method

```
hide
student1.display()
```

Executes the method for that specific object.

Accessing Attributes

You can directly access object attributes using the dot (.) operator:

```

print(student1.name)
print(student2.roll)

```

Notes

 Real-Life Example

class->Blueprint of a Car

Defines structure: engine, wheels, color.

Objects->Actuals cars

Each car follows the same structure but has different values.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges