0
0
Pythonprogramming~5 mins

Accessing and modifying attributes in Python

Choose your learning style9 modes available
Introduction

Attributes store information about an object. Accessing and changing them lets you see or update that information.

You want to check the details of a person stored in a program.
You need to update the score of a player in a game.
You want to change the color of a shape on the screen.
You want to read or change settings saved in an object.
Syntax
Python
object.attribute  # to access
object.attribute = new_value  # to modify

Use dot . to get or set an attribute.

Make sure the attribute exists before accessing it to avoid errors.

Examples
Access the color attribute of my_car.
Python
class Car:
    def __init__(self, color):
        self.color = color

my_car = Car('red')
print(my_car.color)
Modify the color attribute to a new value.
Python
my_car.color = 'blue'
print(my_car.color)
Access and then update the age attribute of a Person object.
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person('Anna', 30)
print(p.age)
p.age = 31
print(p.age)
Sample Program

This program creates a Book object, shows its attributes, then changes the author and shows the new value.

Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

book1 = Book('Python Basics', 'Sam')

# Access attributes
print(f"Title: {book1.title}")
print(f"Author: {book1.author}")

# Modify attribute
book1.author = 'Alex'
print(f"Updated Author: {book1.author}")
OutputSuccess
Important Notes

Trying to access an attribute that does not exist will cause an error.

You can add new attributes by assigning them, like object.new_attr = value.

Summary

Use dot notation to get or set attributes on objects.

Attributes hold data about the object.

Changing attributes updates the object's information.