How to create Class

🟥 Rectangle Properties

Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position.

Examples:

  • ↔️ width: The length of the horizontal side of the rectangle.
  • ↕️ height: The length of the vertical side of the rectangle.
  • 🎯 x_position: The horizontal coordinate of the rectangle’s top-left corner.
  • 🎯 y_position: The vertical coordinate of the rectangle’s top-left corner.
  • 🎨 color: The color used to fill or outline the rectangle (e.g., 'red', 'blue').

📐 Rectangle Methods

Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information about the rectangle or change its properties.

Examples:

  • calculate_area(): A method that computes and returns the area of the rectangle by multiplying the width and height.
  • 📏 calculate_perimeter(): A method that computes and returns the perimeter of the rectangle (e.g., 2 * (width + height)).
  • 🚶 move(new_x, new_y): A method that updates the x_position and y_position properties to a new location.
  • 📈 resize(new_width, new_height): A method that changes the width and height properties of the rectangle.
  • 🖼️ draw(): A method that renders the rectangle on a screen using its x_position, y_position, width, height, and color properties.

Python

class Rectangle:

    def __init__(self):
        self.length = 10
        self.breadth = 5

    def area(self):
        return self.length * self.breadth

    def perimeter(self):
        return 2 * (self.length + self.breadth)


r = Rectangle()
print('Length', r.length)
print('Breadth', r.breadth)
print('Area', r.area())
print('Perimeter', r.perimeter())

Class Syntax

The basic syntax for creating a class in Python is as follows:

Python

class ClassName:
    # Class body goes here
    # This can include properties and methods
  • class: This is a required keyword that tells Python you are defining a new class.
  • ClassName: This is the name you give to your class. By convention, class names are in PascalCase (each word starts with a capital letter, with no underscores, e.g., MyClass, BankAccount).
  • :: A colon at the end of the class name is mandatory.

Creating a Class: Step-by-Step

Let’s use a simple Dog class as an example.

1. The Class Definition

Start by defining the class with the class keyword. This creates the blueprint.

Python

class Dog:

2. The Constructor (__init__)

The constructor is a special method named __init__ (short for “initialize”). It’s called automatically when you create a new object from the class. It’s used to set up the initial properties of the object.

Python

    def __init__(self, name, age):
        self.name = name  # Property 1
        self.age = age    # Property 2
  • self: The first parameter in every method of a class, including __init__. It refers to the specific instance of the object being created. You use it to attach properties to the object (e.g., self.name).
  • name and age: These are additional parameters that you can pass when creating a Dog object. They are used to set the initial values of the name and age properties.

3. Adding Methods

Add methods to define the actions the object can perform. Methods are just functions defined within the class. They also take self as their first parameter.

Python

    def bark(self):
        print(f"{self.name} says Woof!")
  • self.name: The bark method uses self to access the name property of the specific Dog object that is calling the method.

4. Putting It All Together

Here’s the full class definition:

Python

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

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

    def get_info(self):
        return f"{self.name} is a {self.age}-year-old dog."

5. Creating an Object

To use the class, you create an object (also called an instance) from it. You pass arguments to the constructor to set the initial properties.

Python

# Creating a new Dog object named 'Buddy'
my_dog = Dog("Buddy", 5)

Now, my_dog is an object with its own name and age properties. You can access its properties and call its methods using dot notation:

Python

print(my_dog.name)        # Output: Buddy
print(my_dog.get_info())  # Output: Buddy is a 5-year-old dog.
my_dog.bark()             # Output: Buddy says Woof!

self and Constructor

🎯 The self Parameter

The self parameter is a reference to the instance of the class. It’s the first parameter of every method within a class, including the constructor. When you call a method on an object, Python automatically passes the object itself as the self argument.

  • It refers to the object: You use self to access the properties and methods of the specific object you’re working with. It’s how a method knows which object’s data to use. For example, in a Dog class, self.name refers to the name of that specific dog, not a generic one.
  • It’s a convention: self is not a reserved keyword in Python, but it’s a strong, widely-followed convention. You could technically name it something else, but it would make your code confusing for other developers.

🔨 The __init__ Constructor

The __init__ method is a special method that serves as the constructor for a class. Its purpose is to initialize the object’s state right after it has been created.

  • Initialization, not creation: The __init__ method doesn’t create the object itself; it’s called on the newly created object to set its initial properties.
  • Sets the initial state: You use __init__ to assign values to the object’s properties. For example, a Person class might take name and age as arguments in its constructor to set the initial self.name and self.age properties.
  • Syntax: The method name must be exactly __init__ (with two underscores before and after). It always takes self as its first parameter. You can add other parameters to pass data when creating the object.

Here’s an example to illustrate both concepts:

Python

class Car:
    # This is the constructor
    def __init__(self, color, brand):
        # The 'self' keyword assigns values to the object's properties
        self.color = color
        self.brand = brand

    # This is a regular method
    def display_info(self):
        # 'self' is used here to access the object's properties
        print(f"This is a {self.color} {self.brand} car.")

# Creating an object, which automatically calls the __init__ method
my_car = Car("blue", "Ford")

# Calling a method on the object, which automatically passes 'my_car' as 'self'
my_car.display_info()

Similar Posts

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • Method Overloading

    Python does not support traditional method overloading in the way languages like C++ or Java do. If you define multiple methods with the same name, the last definition will simply overwrite all previous ones. However, you can achieve the same result—making a single method behave differently based on the number or type of arguments—using Python’s…

  • Python and PyCharm Installation on Windows: Complete Beginner’s Guide 2025

    Installing Python and PyCharm on Windows is a straightforward process. Below are the prerequisites and step-by-step instructions for installation. Prerequisites for Installing Python and PyCharm on Windows Step-by-Step Guide to Install Python on Windows Step 1: Download Python Step 2: Run the Python Installer Step 3: Verify Python Installation If Python is installed correctly, it…

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

  • Python Calendar Module

    Python Calendar Module The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations. Importing the Module python import calendar Key Methods in the Calendar Module 1. calendar.month(year, month, w=2, l=1) Returns a multiline string with a calendar for the specified month….

  • Python Installation Guide: Easy Steps for Windows, macOS, and Linux

    Installing Python is a straightforward process, and it can be done on various operating systems like Windows, macOS, and Linux. Below are step-by-step instructions for installing Python on each platform. 1. Installing Python on Windows Step 1: Download Python Step 2: Run the Installer Step 3: Verify Installation If Python is installed correctly, it will…

Leave a Reply

Your email address will not be published. Required fields are marked *