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

Leave a Reply

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