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.
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