Class Attributes
Class Attributes

Class Attributes

Introduction

When we design a class attributes, we use instance variables and class variables.

In Class, attributes can be defined into two parts:

  1. Instance variables
  2. Class Variables
image

Instance Variables vs. Class Variables in Python

When designing a class in Python, we work with attributes (data stored in objects). These attributes fall into two categories:

  • Instance Variables (specific to each object/instance).
  • Class Variables (shared across all instances of the class).

Instance Variables

Definition

  • Instance variables are unique to each object created from a class.
  • They are defined inside the constructor (__init__() method) or other instance methods using the keyword self.
  • Each object has its own copy of instance variables.

Key Characteristics

  • Belong to one object only.
  • Defined with the prefix self..
  • Values can differ across instances of the class.
  • Can be modified for each object without affecting others.

Class Variables

Definition

  • Class variables are shared across all objects of a class.
  • Defined inside the class body, but outside of any methods.
  • Only one copy exists, and all instances refer to the same variable.

Key Characteristics

  • Belong to the class itself, not individual objects.
  • Defined directly in the class body (without self).
  • Any change to a class variable affects all objects (unless overridden at the instance level).
  • Often used for constants, counters, or shared properties.

Python Class Variables

Python Instance Variables

In Object-oriented programming, when we design a class, we use instance variables and class variables.

  • Instance variables: If the value of a variable varies from object to object, then such variables are called instance variables.
  • Class Variables: A class variable is a variable that is declared inside of class, but outside of any instance method or __init__() method.

What is an Instance Variable in Python?

image

Create Instance Variables

Instance variables are declared inside a method using the self keyword. We use a constructor to define and initialize the instance variables. Let’s see the example to declare an instance variable in Python.

Example:

In the following example, we are creating two instance variable name and age in the Studentclass.

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

# create first object
s1 = Student("Jessa", 20)

# access instance variable
print('Object 1')
print('Name:', s1.name)
print('Age:', s1.age)

# create second object
s2= Student("Kelly", 10)

# access instance variable
print('Object 2')
print('Name:', s2.name)
print('Age:', s2.age)

output

Object 1
Name: Jessa
Age: 20

Object 2
Name: Kelly
Age: 10

Note:

  • When we created an object, we passed the values to the instance variables using a constructor.
  • Each object contains different values because we passed different values to a constructor to initialize the object.
  • Variable declared outside __init__() belong to the class. They’re shared by all instances.

Modify Values of Instance Variables

We can modify the value of the instance variable and assign a new value to it using the object reference.

Note: When you change the instance variable’s values of one object, the changes will not be reflected in the remaining objects because every object maintains a separate copy of the instance variable.

Example

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

# create object
stud1 = Student("Jessa", 20)
stud2 = Student("Kelly", 10)
stud3 = Student("Emma", 15)
# modify instance variable for student 1 only 
stud1.name = 'Emma'
stud1.age = 15
print('Before')
print('Name:', stud1.name, 'Age:', stud1.age)

print("-" * 50)

print('After')
print('Name:', stud1.name, 'Age:', stud1.age)

output

Before
Name: Emma Age: 15
--------------------------------------------------
After
Name: Emma Age: 15

Three Methods of Accessing Instance Variables

When working with Python classes, there are three primary ways to access instance variables (attributes). Each method has its specific use cases, advantages, and appropriate scenarios. Let's explore each method in detail using our Product class example.

  • Method 1: Using self Within Instance Methods
  • Method 2: Direct Access Using Dot Notation
  • Method 3: Using getattr() Function

Method 1: Using self Within Instance Methods

Method 2: Direct Access Using Dot Notation

Method 3: Using getattr() Function

Comparison Summary

Aspect
Method 1 (self)
Method 2 (Direct)
Method 3 (getattr())
Location
Inside class methods
Outside class
Anywhere
Performance
Medium
Fastest
Slowest
Error Handling
Manual
None
Built-in
Default Values
Manual
Not supported
Built-in
Encapsulation
Best
Poor
Medium
Flexibility
High
Low
Highest
Use Case
Internal operations
Simple access
Dynamic/safe access

Best Practices

Use Method 1 (self) when:

  • Writing methods inside the class
  • Implementing business logic
  • Need to access multiple attributes of the same object
  • Want to maintain proper OOP encapsulation

Use Method 2 (Direct Access) when:

  • Quick, simple attribute access
  • Performance is critical
  • Working with trusted, stable attributes
  • Building simple scripts or prototypes

Use Method 3 (getattr()) when:

  • Attribute existence is uncertain
  • Need default values for missing attributes
  • Building generic, reusable functions
  • Working with dynamic attribute names
  • Need robust error handling

Conclusion

Each method serves its purpose in Python programming. Understanding when and how to use each approach will make you a more effective Python developer. The key is choosing the right method based on your specific needs: security, performance, flexibility, and error handling requirements.