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.")
In the above example, we have a
Car class that represents a car object. The class has several attributes such as
These attributes are defined within the
__init__ method, which is the constructor method in Python.
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
In the above code, we create an instance of the
Car class called
We can access its attributes using dot notation, such as
We can also modify the attribute values, as shown when we call the
- Simple Python Script Example [Super Simple!]
- K-means Clustering for Anomaly Detection
- What is f’ Python [With Examples]
- Is Python Similar to R [Easier Than Python?]
- Best Python Library to Detect Language
- How do I write a YAML file in Python?
- What is Statement in Python With Example?
- What is ‘Self’ in Python With Example
- The Programming Cycle for Python With Example
- How to Use f.write in Python? [Write in a Text File]
- What is Token in Python With Example
- List I j in Python [Detailed Examples]