Classes

What is a Class?

A class in Python is a blueprint for creating objects. Objects represent real-world entities with properties (attributes) and actions (methods). Using classes, you can organize and reuse code efficiently.


Why Use Classes?

  • To group related data and functions together.

  • To create multiple objects with similar structure but different data.

  • To model real-world things (like students, cars, animals) in code.


Defining a Simple Class

Here is how you define a basic class in Python:

class Person:
    pass

The pass statement means "do nothing". This class doesn't do anything yet.


Adding Attributes

Attributes are variables that belong to the object. You define them using a special method called __init__.

  • __init__: This is called the constructor. It runs when you create a new object.

  • self: Refers to the current object being created.


Creating Objects (Instances) from a Class

You can create objects by calling the class like a function:


Adding Methods

Methods are functions defined inside a class. They describe what objects can do.


Example: A Simple Student Class


Summary

  • Class: A blueprint for objects.

  • Object: An instance of a class.

  • Attributes: Variables that belong to an object.

  • Methods: Functions that belong to an object.

  • Use __init__ to set up initial values.


Practice

Try writing your own class, for example, a Car class with attributes like make and year, and a method to display information.

Last updated

Was this helpful?