class keyword is used to create a class in Python. A class acts as a blueprint for creating objects that contain their own data and functions.
class Car:
def show(self):
print("This is a car.")
car = Car()
car.show()
Output
This is a car.
Explanation: class Car: statement creates a class named Car. The object car is created using Car(), and calling car.show() executes the show() method, which prints the message.
Syntax
class ClassName:
def method(self):
pass
Parameters:
- ClassName: The name of the class.
- method: A function defined inside the class that describes the behavior of its objects.
- self: Refers to the current object and is used to access its attributes and methods.
Returns: Creates a new class, which can be used to create objects.
Examples
Example 1: Here, we create a class with an attribute and access its value using an object.
class Student:
def __init__(self, name):
self.name = name
student = Student("David")
print(student.name)
Output
David
Explanation: __init__() method initializes the name attribute when the object is created. The value is accessed using student.name.
Example 2: Here, we define a method inside a class and call it using an object.
class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
print(calc.add(10, 20))
Output
30
Explanation: object calc calls the add() method with the values 10 and 20. The method returns their sum.
Example 3: Here, we create multiple objects from the same class, where each object stores its own data.
class Product:
def __init__(self, name):
self.name = name
product1 = Product("Laptop")
product2 = Product("Keyboard")
print(product1.name)
print(product2.name)
Output
Laptop Keyboard
Explanation: Both product1 and product2 are created from the same Product class, but each object stores a different value for the name attribute.
Example 4: Here, we modify the value of an object's attribute after it has been created.
class Employee:
def __init__(self):
self.salary = 30000
employee = Employee()
employee.salary = 35000
print(employee.salary)
Output
35000
Explanation: salary attribute is initialized with 30000. Later, its value is updated to 35000 using the object employee.
Example 5: Here, we define multiple methods inside a class to perform different operations.
class Rectangle:
def area(self, length, width):
return length * width
def perimeter(self, length, width):
return 2 * (length + width)
rect = Rectangle()
print(rect.area(5, 4))
print(rect.perimeter(5, 4))
Output
20 18
Explanation: class contains two methods: area() calculates the area of the rectangle, while perimeter() calculates its perimeter. Both methods are called using the rect object.