HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Create a Class with Attributes

Creating a class with attributes in Python is a fundamental aspect of object-oriented programming (OOP). In python, classes allow you to define a blueprint for creating objects, and attributes are the characteristics or even called as the properties of objects.

I’ll write now a detailed example to show you how to create a class with attributes in Python.

class Car:
    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color
        self.mileage = 0  # Default mileage is set to 0

    def drive(self, miles):
        """Simulate driving the car and updating its mileage."""
        self.mileage += miles

    def display_info(self):
        """Display information about the car."""
        print(f"Make: {self.make}")
        print(f"Model: {self.model}")
        print(f"Year: {self.year}")
        print(f"Color: {self.color}")
        print(f"Mileage: {self.mileage} miles")

Let me explain the above code now.

  1. The example Car class is defined using the class keyword.
  2. The __init__ method is a special method in Python classes that is called when a new instance of the class is created. It initializes the attributes of the class. In this example, it initializes make, model, year, color, and mileage attributes. self is a reference to the instance of the class.
  3. Attributes – The make, model, year, color, and mileage are attributes of the Car class. They store information about each car object.
    Instance Methods:
  4. drive(self, miles) – This method simulates driving the car and updating its mileage. It takes the argument miles, which represents the distance driven, and updates the mileage attribute accordingly.
  5. display_info(self) – This method displays information about the car, including its make, model, year, color, and mileage.

Let’s complete the above code and here is the working example, you can just copy and use it.

class Car:
    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color
        self.mileage = 0  # Default mileage is set to 0

    def drive(self, miles):
        """Simulate driving the car and updating its mileage."""
        self.mileage += miles

    def display_info(self):
        """Display information about the car."""
        print(f"Make: {self.make}")
        print(f"Model: {self.model}")
        print(f"Year: {self.year}")
        print(f"Color: {self.color}")
        print(f"Mileage: {self.mileage} miles")

# Creating instances of the Car class
car1 = Car("Toyota", "Camry", 2020, "Red")
car2 = Car("Honda", "Accord", 2018, "Silver")

# Displaying information about the cars
print("Car 1:")
car1.display_info()
print("\nCar 2:")
car2.display_info()

# Driving car 1 for 150 miles and car 2 for 200 miles
car1.drive(150)
car2.drive(200)

# Displaying updated mileage
print("\nAfter driving:")
print("Car 1 Mileage:", car1.mileage, "miles")
print("Car 2 Mileage:", car2.mileage, "miles")

When you run the above code, the following is the expected output:

Car 1:
Make: Toyota
Model: Camry
Year: 2020
Color: Red
Mileage: 0 miles

Car 2:
Make: Honda
Model: Accord
Year: 2018
Color: Silver
Mileage: 0 miles

After driving:
Car 1 Mileage: 150 miles
Car 2 Mileage: 200 miles

Before we conclude, make sure you understand the following key points about Python class attributes:

  • Encapsulation – Class attributes encapsulate data within the class, ensuring data integrity and providing a clear interface for interacting with objects.
  • Initialization – Class attributes are typically initialized in the constructor (`__init__` method) using the `self` keyword to refer to the instance.
  • Access and Modification – Class attributes can be accessed and modified using dot notation (`object.attribute`) both inside and outside the class.
  • Shared Attributes – Class attributes can also be shared among all instances of a class, acting as shared data across all objects of that class.

Class attributes in Python are very commonly used, If you follow the above example you must be able to easily understand the concept.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Object-Oriented Programming
Up Next
Python Code to Define Methods in a Class
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.