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

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

  • positive lookbehind assertion

    A positive lookbehind assertion in Python’s re module is a zero-width assertion that checks if the pattern that precedes it is present, without including that pattern in the overall match. It’s the opposite of a lookahead. It is written as (?<=…). The key constraint for lookbehind assertions in Python is that the pattern inside the…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

Leave a Reply

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