0
0
Pythonprogramming~5 mins

Class definition syntax in Python

Choose your learning style9 modes available
Introduction

Classes help you group related data and actions together. They let you create your own types to organize code better.

When you want to model real-world things like a car or a person in your program.
When you need to keep data and functions that work on that data together.
When you want to create many similar objects with shared behavior.
When you want to reuse code by creating new classes based on existing ones.
When you want to keep your code organized and easier to understand.
Syntax
Python
class ClassName:
    def __init__(self, parameters):
        # initialize attributes
    
    def method_name(self, parameters):
        # method actions

The class keyword starts the class definition.

The __init__ method sets up the object when created.

Examples
A simple class Dog with a name and a bark method.
Python
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says Woof!")
Class Car stores brand and year, and shows info.
Python
class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

    def info(self):
        print(f"{self.brand} made in {self.year}")
Sample Program

This program defines a Person class with name and age. It creates a person named Alice and calls the greet method to say 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.")

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

Always use self as the first parameter in methods to access object data.

Indentation is important to group code inside the class.

Class names usually start with a capital letter by convention.

Summary

Classes group data and functions to model real-world things.

Use class keyword and define an __init__ method to set up objects.

Methods inside classes use self to access object data.