0
0
Pythonprogramming~5 mins

Adding custom attributes in Python

Choose your learning style9 modes available
Introduction

Custom attributes let you add extra information to objects. This helps you store and use data that fits your needs.

You want to remember a person's nickname in a user profile object.
You need to track if a task is completed in a task object.
You want to add a color label to items in a list.
You want to store extra settings on a configuration object.
Syntax
Python
object.attribute_name = value

You can add any attribute name you want.

The value can be any data type like number, text, or even another object.

Examples
This adds a new attribute color with value 'red' to the my_car object.
Python
class Car:
    pass

my_car = Car()
my_car.color = 'red'
Here, age is added after the object is created.
Python
class Person:
    def __init__(self, name):
        self.name = name

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

This program creates a Book object with a title. Then it adds a custom attribute author and prints both.

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

my_book = Book('Python Basics')
my_book.author = 'Sam'
print(f"Title: {my_book.title}")
print(f"Author: {my_book.author}")
OutputSuccess
Important Notes

You can add custom attributes anytime after creating the object.

Be careful not to overwrite existing attributes unless you want to change them.

Summary

Custom attributes let you add extra data to objects.

Use object.attribute = value to add them.

This helps keep related information together in one place.