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:
-
Attributes → data (variables)
-
Methods → behavior (functions)
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:
-
Memory is allocated
-
The class blueprint becomes a usable entity
Each object can have different values for its attributes but shares the same structure.
Example: Creating a Class and Object
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
-
A class groups related data and behavior together.
-
An object is a real-world entity created from a class.
-
The dot operator is used to access attributes and methods.
The __init__() method automatically runs during object creation.
Real-Life Example
class->Blueprint of a Car
Defines structure: engine, wheels, color.
Objects->Actuals cars
-
Car1 (Red, BMW)
-
Car2 (Blue, Tesla)
-
Car3 (Black, Audi)
Each car follows the same structure but has different values.
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges