0
0
Pythonprogramming~5 mins

Classes and objects in Python

Choose your learning style9 modes available
Introduction

Classes help you create your own blueprints for things. Objects are the actual things made from those blueprints.

When you want to group related data and actions together, like a car with color and speed.
When you want to create many similar things, like many dogs with different names.
When you want to organize your code better by keeping data and functions in one place.
When you want to model real-world things in your program, like a bank account or a book.
Syntax
Python
class ClassName:
    def __init__(self, parameters):
        self.attribute = value

    def method(self):
        # code here

# Create an object
obj = ClassName(arguments)

class defines a new blueprint.

__init__ is a special method that runs when you make a new object.

Examples
This creates a Dog with a name and a bark action.
Python
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says Woof!")

my_dog = Dog("Buddy")
my_dog.bark()
This creates a Car with color and speed, then drives it.
Python
class Car:
    def __init__(self, color, speed):
        self.color = color
        self.speed = speed

    def drive(self):
        print(f"Driving at {self.speed} km/h")

car1 = Car("red", 100)
car1.drive()
Sample Program

This program creates a Person named Alice who is 30 years old and then says hello.

Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

person1 = Person("Alice", 30)
person1.greet()
OutputSuccess
Important Notes

Use self to refer to the current object inside methods.

You can create many objects from one class, each with its own data.

Classes help keep your code organized and easy to understand.

Summary

Classes are blueprints for creating objects.

Objects hold data and can do actions defined by their class.

Use classes to model real-world things and organize your code.