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:
Python Glossary
Next article icon

Python Class Members

Last Updated : 17 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Python, similarly to other object-oriented allows the user to write short and beautiful code by enabling the developer to define classes to create objects.

The developer can define the prototype of an object class based on two types of members:

  • Instance members
  • Class members

In the real world, these may look similar in many ways but in actuality, these are a lot different in terms of their use cases.

To understand Class members, let us recall how the instance members work:

Instance members

Instance variables in python are such that when defined in the parent class of the object are instantiated and separately maintained for each and every object instance of the class. These are usually called using the self. Keyword. The self keyword is used to represent an instance of the class

Instance variables can be defined as following using self. with the variable

Python3
# for example we define the following # class with a instance variable  class Node:   def __init__(self):          # this is a instance variable     self.msg = "This is stored in an instance variable."   # instance variables can be used as following print(Node().msg) 

Output:

This is stored in an instance variable.

Note: the instance variables can only be called once the class is instantiated into an object.

In order for a method to be an instance method it needs to be passed the self attribute. Instance methods can be defined as follows:

Python3
# for example we define the following # class with a instance variable class Node:     def __init__(self):              # this is a instance variable       self.msg = "This is stored in an instance variable."        # following is an instance method     def func(self):         print('This was printed by an instance method.')         return self.msg   # instance methods can be used as following print(Node().func()) 

Output:

This was printed by an instance method.  This is stored in an instance variable.

Now that we all understand the basics of instance members in Python, Let us now understand how the class members in python work and how they may be implemented.

Class members

Class members may be defined in the scope of the class. These may usually be used with the cls keyword. The cls keyword is similar to the self keyword but unlike the self keyword, it represents the class itself.

Class variables can be declared in the class outside the methods without using any keyword. The following is how to implement Class Variables:

Python3
# we define the following class with a instance variable  class Node:   cls_msg = "This is stored in an class variable."   def __init__(self):          # this is a instance variable     self.msg = "This is stored in an instance variable."    print(Node.cls_msg) print(Node().cls_msg) 

Output:

This is stored in an class variable.  This is stored in an class variable.

Note: The Class members are available both in an instantiated object of a class as well as for an uninstantiated class.

Class methods need to be defined using the @classmethod decorator and need to be passed a cls attribute as follows:

Python3
# here, we will add a class method to the same class class Node:   cls_msg = "This is stored in an class variable."   def __init__(self):     self.msg = "This is stored in an instance variable." # this is a instance variable    # now we define a class method   @classmethod   def func(cls):     print('This was printed by a class method.')     return cls.cls_msg  print(Node.func()) print(Node().func()) 

Output:

This was printed by a class method.  This is stored in an class variable.  This was printed by a class method.  This is stored in an class variable.

Self vs cls Python

Note: cls works a lot similar to self. Following are some major differences:

self

cls

self works in the scope of the instance.

 cls works in the scope of the class.

self can be used to access both, the members of the 

instance as well as that of the class.

cls can only be used to access the class members. 

 Modifying a class variable

We can not modify a class variable from an instance it can only be done from the class itself.

In case we try to modify a class variable from an instance of the class, an instance variable with the same name as the class variable will be created and prioritized by the attribute lookup.

Implementation

Following snippet shows an example of class attribute modification:

Python3
# we define the following class with an instance variable  class Node:   cls_msg = "This is stored in an class variable."  # instantiate an object instance1 = Node()  print('Before any modification:') print(instance1.cls_msg) print(Node.cls_msg) print('\n')  # Try to modify a class variable through an instance instance1.cls_msg = 'This was modified.'  print('After modifying class variable through an instance:') print(instance1.cls_msg) print(Node.cls_msg) print('\n')  # instantiate the same object again instance1 = Node()  # Modifying a class variable through the class itself Node.cls_msg = 'This was modified.'  print('After modifying class variable through a Class:') print(instance1.cls_msg) print(Node.cls_msg) 
Before any modification:  This is stored in an class variable.  This is stored in an class variable.      After modifying class variable through an instance:  This was modified.  This is stored in an class variable.      After modifying class variable through a Class:  This was modified.  This was modified.

Modifying a class variable containing mutable objects (list, dictionaries, etc.)

Modifying a class variable that contains mutable objects can yield interesting results.

let us see with an example:

Python3
# we define the following class with an instance variable  class Node:   cls_msg = ['This was already here.']  # instantiate an object instance1 = Node()  print('Before any modification:') print(Node.cls_msg) print('\n')  # Try to modify a class variable through an instance instance1.cls_msg.append('This was added in from an instance.')  print('After modifying class variable through an instance:') print(Node.cls_msg) print('\n')  # instantiate the same object again instance1 = Node()  # Modifying a class variable through the class itself Node.cls_msg.append('This was added in from the class.')  print('After modifying class variable through a Class:') print(Node.cls_msg) 
Before any modification:  ['This was already here.']      After modifying class variable through an instance:  ['This was already here.', 'This was added in from an instance.']      After modifying class variable through a Class:  ['This was already here.', 'This was added in from an instance.', 'This was added in from the class.']

Finally,  This can be concluded that class members in python can be very helpful in the real world and can have a wide range of interesting use cases if implemented properly.


Next Article
Python Glossary

D

dipans9p4h
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Python Access Set Items
    Python sets are unordered collections of unique elements. Unlike lists or dictionaries, sets do not have indices so accessing elements in the traditional way using an index doesn't apply. However, there are still ways to work with sets and access their items effectively. This article will guide you
    2 min read
  • Python Glossary
    Python is a beginner-friendly programming language, widely used for web development, data analysis, automation and more. Whether you're new to coding or need a quick reference, this glossary provides clear, easy-to-understand definitions of essential Python terms—listed alphabetically for quick acce
    5 min read
  • Python Access Tuple Item
    In Python, a tuple is a collection of ordered, immutable elements. Accessing the items in a tuple is easy and in this article, we'll explore how to access tuple elements in python using different methods. Access Tuple Items by IndexJust like lists, tuples are indexed in Python. The indexing starts f
    2 min read
  • Literals in Python
    Literals in Python are fixed values written directly in the code that represent constant data. They provide a way to store numbers, text, or other essential information that does not change during program execution. Python supports different types of literals, such as numeric literals, string litera
    5 min read
  • Create Class Objects Using Loops in Python
    We are given a task to create Class Objects using for loops in Python and return the result, In this article we will see how to create class Objects by using for loops in Python. Example: Input: person_attributes = [("Alice", 25), ("Bob", 30), ("Charlie", 35)]Output: Name: Alice, Age: 25, Name: Bob,
    4 min read
  • Interesting Facts About Python
    Python is a high-level, general-purpose programming language that is widely used for web development, data analysis, artificial intelligence and more. It was created by Guido van Rossum and first released in 1991. Python's primary focus is on simplicity and readability, making it one of the most acc
    7 min read
  • How to write memory efficient classes in Python?
    Memory efficiency is a critical aspect of software development, especially when working with resource-intensive applications. In Python, crafting memory-efficient classes is essential to ensure optimal performance. In this article, we'll explore some different methods to write memory-efficient class
    2 min read
  • How to Import Other Python Files?
    We have a task of how to import other Python Files. In this article, we will see how to import other Python Files. Python's modular and reusable nature is one of its strengths, allowing developers to organize their code into separate files and modules. Importing files in Python enables you to reuse
    3 min read
  • Python Program to Get the Class Name of an Instance
    In this article, we will see How To Get a Class Name of a class instance. For getting the class name of an instance, we have the following 4 methods that are listed below: Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.Use the type() function and
    4 min read
  • 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
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