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 thewidthandheight. - 📏
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 thex_positionandy_positionproperties to a new location. - 📈
resize(new_width, new_height): A method that changes thewidthandheightproperties of the rectangle. - 🖼️
draw(): A method that renders the rectangle on a screen using itsx_position,y_position,width,height, andcolorproperties.
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).nameandage: These are additional parameters that you can pass when creating aDogobject. They are used to set the initial values of thenameandageproperties.
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: Thebarkmethod usesselfto access thenameproperty of the specificDogobject 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
selfto 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 aDogclass,self.namerefers to the name of that specific dog, not a generic one. - It’s a convention:
selfis 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, aPersonclass might takenameandageas arguments in its constructor to set the initialself.nameandself.ageproperties. - Syntax: The method name must be exactly
__init__(with two underscores before and after). It always takesselfas 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()