What is Attribute in Python With Example

An attribute is a value associated with an object. It can be thought of as a variable that belongs to a specific object.

Attributes store information about the object’s state and behavior.

They can be accessed and modified using dot notation.

Here’s an example to illustrate attributes in Python:

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.is_running = False
    
    def start_engine(self):
        self.is_running = True
        print("The engine is now running.")
    
    def stop_engine(self):
        self.is_running = False
        print("The engine has been stopped.")
Code language: Python (python)

In the above example, we have a Car class that represents a car object. The class has several attributes such as make, model, year, and is_running.

These attributes are defined within the __init__ method, which is the constructor method in Python.

The is_running attribute is a boolean value indicating whether the car’s engine is running.

We can create an instance of the Car class and access its attributes as follows:

my_car = Car("Toyota", "Camry", 2022)
print(my_car.make)  # Output: Toyota
print(my_car.model)  # Output: Camry
print(my_car.year)  # Output: 2022
print(my_car.is_running)  # Output: False

my_car.start_engine()  # Output: The engine is now running.
print(my_car.is_running)  # Output: True

my_car.stop_engine()  # Output: The engine has been stopped.
print(my_car.is_running)  # Output: False
Code language: Python (python)

In the above code, we create an instance of the Car class called my_car.

We can access its attributes using dot notation, such as my_car.make, my_car.model, etc.

We can also modify the attribute values, as shown when we call the start_engine() and stop_engine() methods.

Read More;

  • Dmytro Iliushko

    I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

    View all posts

Leave a Comment