Python

How to write a Python class with methods and attributes?

Creating Python Classes with Methods and Attributes: A Beginner's Guide

Introduction: Python classes are fundamental for organizing code into reusable and structured components. In this guide, we'll walk through the process of creating a Python class, defining attributes, and implementing methods, empowering you to leverage the power of object-oriented programming in Python.


1. Defining a Simple Class:

class Car:
def __init__(self, make, model, year):
    self.make = make
    self.model = model
    self.year = year
# Creating an instance of the class
my_car = Car("Toyota", "Camry", 2022)

The __init__ method is a special method called when an object is created. It initializes the attributes of the class.


2. Adding Methods to the Class:

class Car
def __init__(self, make, model, year):
   self.make = make
   self.model = model
   self.year = year
def display_info(self):
   print(f"{self.year} {self.make} {self.model}")
# Creating an instance of the class
my_car = Car("Toyota", "Camry", 2022)
# Calling a method
my_car.display_info()
# Output: 2022 Toyota Camry

Methods are functions within a class that perform specific actions. In this example, display_info prints information about the car.


3. Updating Attributes with Methods:

class Car:
def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.mileage = 0
 
def drive(self, miles):
     self.mileage += miles
# Creating an instance of the class
my_car = Car("Toyota", "Camry", 2022)
# Calling a method to update an attribute
my_car.drive(50)
# Accessing the updated attribute
print(my_car.mileage) # Output: 50

Methods can modify the attributes of the class, as shown in the drive method, which updates the mileage.


4. Using Class Inheritance:

class ElectricCar(Car):
       def __init__(self, make, model, year, battery_capacity):
          super().__init__(make, model, year)
                   self.battery_capacity = battery_capacity
      def display_info(self):
           print(f"{self.year} {self.make} {self.model} (Electric)")
# Creating an instance of the subclass
my_electric_car = ElectricCar("Tesla", "Model S", 2022, 100)
# Overriding a method from the parent class
my_electric_car.display_info() # Output: 2022 Tesla Model S (Electric)

Inheritance allows a new class (ElectricCar) to inherit attributes and methods from an existing class (Car).


Conclusion:

Creating Python classes with methods and attributes is a foundational skill in object-oriented programming. By defining classes, organizing data, and encapsulating functionality, you can build modular and maintainable code in Python.

  • Leave Comment about this Article

    Rating

review

0 Comments