How to create Class

UpComing SoftWare Training Demos

๐Ÿš€ *Playwright With AI Testing Demo In Telugu*
๐Ÿ—“๏ธ *Date:* 28 Oct2026, 08:00 PM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/3r
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/3w
๐Ÿ’ก *Course Content:*
https://www.vlrt.in/3c
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/3v

๐Ÿš€ *Gen AI Engineer (Production Focused)*
๐Ÿ—“๏ธ *Date:* 29th Oct 2026, 06:00PM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/gr
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/gw
๐Ÿ’ก*Course Content:*
https://www.vlrt.in/ai
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/gv

๐Ÿš€ *Vulnerability Management Training Demo*
๐Ÿ—“๏ธ *Date:* 28th Oct 2026, 10:00 AM IST
๐Ÿ“*Register Now!:*
https://www.vlrt.in/vr
๐Ÿ‘ฅ *Join Community:*
https://www.vlrt.in/cw
๐Ÿ’ก *Course Content:*
https://www.vlrt.in/vc
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/Vm

๐ŸŸฅ 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

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

  • reย module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

  • what is pythonย 

    What is Python? Python is a popular, high-level programming language known for its simplicity and readability. Because its syntax closely resembles everyday English, it is incredibly easy for beginners to learn, read, and write. Despite being beginner-friendly, it is also one of the most powerful languages in the world, used heavily by professionals for artificial…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  • 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…

  • Indexing and Slicing for Writing (Modifying) Lists in Python

    Indexing and Slicing for Writing (Modifying) Lists in Python Indexing and slicing aren’t just for reading lists – they’re powerful tools for modifying lists as well. Let’s explore how to use them to change list contents with detailed examples. 1. Modifying Single Elements (Indexing for Writing) You can directly assign new values to specific indices. Example 1:…

Leave a Reply

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