Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to change any data type into a String in Python?
Next article icon

How to Change Class Attributes By Reference in Python

Last Updated : 07 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We have the problem of how to change class attributes by reference in Python, we will see in this article how can we change the class attributes by reference in Python.

What is Class Attributes?

Class attributes are typically defined outside of any method within a class and are shared among all instances. To change these attributes by reference, you can access and modify them directly through the class name.

Syntax :

class MyClass:

class_attribute = "Original Value"

# Changing class attribute by reference

MyClass.class_attribute = "New Value"

Change Class Attributes By Reference in Python

Below are some of the methods for how to change class attributes by reference in Python:

  • Numeric Class Attribute
  • List Class Attribute
  • Dictionary Class Attribute
  • Class Attribute Using Method

Change Numeric Class Attribute By Reference in Python

In this example, the count class attribute is incremented by reference, and the change is reflected in all instances of the Counter class.

Python3
class Counter:     count = 0  # Increase count by reference Counter.count += 1  # Accessing the updated value print(Counter.count)   

Output
1 

Change List Class Attribute By Reference in Python

In this example, in below code the shared_list class attribute is a list that is modified by reference through the append method. The change is visible in all instances of the SharedList class.

Python3
class SharedList:     shared_list = []  # Append an element by reference SharedList.shared_list.append(42)  # Accessing the updated list print(SharedList.shared_list)  

Output
[42] 

Change Dictionary Class Attribute By Reference in Python

In this example, the settings class attribute is a dictionary. By updating a key in the dictionary by reference, the change is propagated to all instances of the Config class.

Python3
class Config:     settings = {"mode": "normal", "debug": False}  # Update a key in the dictionary by reference Config.settings["debug"] = True  # Accessing the updated dictionary print(Config.settings)   

Output
{'mode': 'normal', 'debug': True} 

Change Class Attribute Using Method By Reference in Python

In this example, the interest_rate class attribute is modified by reference through a class method (increase_interest_rate). This method allows for a more controlled and organized way of updating class attributes.

Python3
class BankAccount:     interest_rate = 0.03      @classmethod     def increase_interest_rate(cls, percentage):         # Modify class attribute by reference through a method         cls.interest_rate += percentage  # Increase interest rate by 1% BankAccount.increase_interest_rate(0.01)  # Accessing the updated interest rate print(BankAccount.interest_rate)   

Output
0.04 

Conclusion

In Conclusion, changing class attributes by reference in Python provides a powerful mechanism for maintaining consistency, centralizing control, and simplifying code. It ensures that modifications to shared variables are reflected across all instances, promoting efficiency and clarity in object-oriented programming. Understanding and leveraging this capability can lead to more robust and maintainable code in various Python application.


Next Article
How to change any data type into a String in Python?

R

rithikkuerm0
Improve
Article Tags :
  • Python
  • Python Programs
  • python-basics
  • python-oop-concepts
Practice Tags :
  • python

Similar Reads

  • Built-In Class Attributes In Python
    Python offers many tools and features to simplify software development. Built-in class attributes are the key features that enable developers to provide important information about classes and their models. These objects act as hidden gems in the Python language, providing insight into the structure
    4 min read
  • How to change any data type into a String in Python?
    In Python, it's common to convert various data types into strings for display or logging purposes. In this article, we will discuss How to change any data type into a string. Using str() Functionstr() function is used to convert most Python data types into a human-readable string format. It is the m
    3 min read
  • AttributeError: can’t set attribute in Python
    In this article, we will how to fix Attributeerror: Can'T Set Attribute in Python through examples, and we will also explore potential approaches to resolve this issue. What is AttributeError: can’t set attribute in Python?AttributeError: can’t set attribute in Python typically occurs when we try to
    3 min read
  • Private Attributes in a Python Class
    In Python, encapsulation is a key principle of object-oriented programming (OOP), allowing you to restrict access to certain attributes or methods within a class. Private attributes are one way to implement encapsulation by making variables accessible only within the class itself. In this article, w
    2 min read
  • How To Make a Subclass from a Super Class In Python
    In Python, you can create a subclass from a superclass using the class keyword, and by specifying the superclass in parentheses after the subclass name. The subclass inherits attributes and behaviors from the superclass, allowing you to extend or modify its functionality while reusing the existing c
    3 min read
  • Shared Reference in Python
    Let, we assign a variable x to value 5, and another variable y to the variable x. x = 5 y = x When Python looks at the first statement, what it does is that, first, it creates an object to represent the value 5. Then, it creates the variable x if it doesn't exist and made it a reference to this new
    4 min read
  • How to Call a Method on a Class Without Instantiating it in Python?
    In Python programming, classes and methods are like building blocks for organizing our code and making it efficient. Usually, we create instances of classes to access their parts—attributes and methods. But sometimes, we might want to use a class or its methods without actually creating an instance.
    3 min read
  • How to Update a Dictionary in Python
    This article explores updating dictionaries in Python, where keys of any type map to values, focusing on various methods to modify key-value pairs in this versatile data structure. Update a Dictionary in PythonBelow, are the approaches to Update a Dictionary in Python: Using with Direct assignmentUs
    3 min read
  • Class as Decorator in Python
    While function-based decorators are widely used, class-based decorators can offer more flexibility and better organization, especially when the decorator needs to maintain state or requires multiple methods to function properly. A Python class decorator is simply a class that implements the __call__
    3 min read
  • Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences