0
0
Pythonprogramming~5 mins

Class attributes in Python

Choose your learning style9 modes available
Introduction

Class attributes store information shared by all objects of a class. They help keep common data in one place.

When you want all objects of a class to share the same value, like a company name for all employees.
To keep track of data that belongs to the class itself, such as counting how many objects have been created.
When you want to set default values that apply to every object unless changed.
To save memory by not repeating the same value inside every object.
Syntax
Python
class ClassName:
    class_attribute = value

Class attributes are defined directly inside the class, but outside any methods.

All instances share the same class attribute unless overridden in the instance.

Examples
Here, species is a class attribute shared by all Dog objects.
Python
class Dog:
    species = "Canis familiaris"
Both car1 and car2 share the same wheels class attribute.
Python
class Car:
    wheels = 4

car1 = Car()
car2 = Car()
print(car1.wheels)  # prints 4
print(car2.wheels)  # prints 4
This class attribute total_books counts how many Book objects are created.
Python
class Book:
    total_books = 0

    def __init__(self):
        Book.total_books += 1
Sample Program

This program shows how the class attribute school_name is shared by all Student objects. Changing it on the class changes it for all students.

Python
class Student:
    school_name = "Greenwood High"

    def __init__(self, name):
        self.name = name

# Create two students
student1 = Student("Alice")
student2 = Student("Bob")

# Print their school name (class attribute)
print(student1.name + " goes to " + student1.school_name)
print(student2.name + " goes to " + student2.school_name)

# Change class attribute
Student.school_name = "Sunrise Academy"

print(student1.name + " now goes to " + student1.school_name)
print(student2.name + " now goes to " + student2.school_name)
OutputSuccess
Important Notes

If you assign a value to a class attribute using an instance (like student1.school_name = 'New School'), it creates a new instance attribute and does not change the class attribute.

Use class attributes for data shared by all instances, and instance attributes for data unique to each object.

Summary

Class attributes hold data shared by all objects of a class.

They are defined inside the class but outside methods.

Changing a class attribute affects all instances unless they have their own attribute with the same name.