What Is The Difference Between Class Variable And Instance Variable In Python

Python classes, all methods of classes and class variables have only one copy in memory, and all instances of one python class share them. Each instance keeps its own and its own instance variables in memory. When an instance is created, in addition to encapsulating instance variables, a class object pointer is saved in the instance also, the pointer points to the address of the class to which the instance belongs. Therefore, an instance can find its own class and make relevant calls, but a class cannot find its instances. This article will tell you how to create python class, class instance, variables and methods.

1. How To Define A Python Class And Create It’s Instance.

Python uses the class keyword to define a class. Its basic structure is as follows.

class class_name (parent class list):

      pass

Class name are usually named in the form of hump, so as to make the literal meaning reflect the function of class. Python adopts multiple inheritance mechanism. A class can inherit multiple parent classes (also known as base class and superclass) at the same time. The inherited base classes have the order and are written in parentheses after the class name. The list of inherited parent classes can be empty, and the parentheses can be omitted.

But in Python 3, even if you define a class which do not explicitly inheriting any parent classes, it also inherits the object class by default. Because object is the base class of all classes in Python 3. Below is an example of python class Worker.

class Worker: 
    
    dept = 'Dev' 
    
    salary = 10000 
    
    def __init__(self, name, age): 
        
        self.name = name 
        
        self.age = age 
        
    def print_age(self): 
        
        print('%s: %s' % (self.name, self.age))

By default, an instance of a class can be generated using a method similar to obj = Worker(). However, each instance of a class usually has its own instance variables, such as name and age. In order to reflect the differences of instances during instantiation, python provides an instantiation method def __init__( self ) :.

In any python class, the method named __init__ is the instantiation method of the class. When the class with __init__ method is instantiated, it will automatically call the method and pass the corresponding parameters to the __init__ method.

jerry = Worker("Jerry", 80)

tom = Worker("Tom", 90)

2. Instance Variable And Class Variable.

2.1 Instance Variable.

Instance variable refers to the variable owned by the instance itself. The variables of each instance are different in memory. In the Worker class, the name and age in the __init__ method are two instance variables. Calling instance variable by adding dot to instance name.

>>>print(jerry.name)
Jerry

>>>print(tom.name)
Tom

2.2 Class Variable.

Variables defined in a class other than methods are called class variables. Class variables are public variables of all instances. Each instance can access and modify class variables. In the Worker class, dept and salary are class variables. Class variables can be accessed by adding a dot to the class name or instance name.

>>>print(Worker.dept)
Dev
  
>>>print(jerry.salary)
10000 

>>>print(tom.salary)
10000

When using instance variables and class variables, be sure to pay attention to that when using variables like jerry.name to access variables, the instance will first find out whether there is an instance variable in its own instance variable list. If not, it will go to the class variable list to find it. If not, an exception will pop up.

Because python is a dynamic language, so it allow us to add new instance variables to instances and new class variables and methods to classes at any time. Below is an example.

# Create two Worker class instances.
>>>jerry = Worker("Jerry", 80) 
>>>tom = Worker("Tom", 90)
    
# Print each worker's age.
>>>print(jerry.age)
80

>>>print(tom.age)
90

# Modify jerry's age to 88.   
>>>jerry.age = 88
>>>print(jerry.age)
88

>>>print(tom.age)
90
    
# A unique instance variable is created for Jerry, but the name is the same as the class variable, which is called salary.
>>>jerry.salary = 20000 
>>>print(Worker.salary)
10000    

# Print newly created instance variable value for instance jerry.
>>>print(jerry.salary)
20000    
    
>>>print(tom.salary)
10000

# Remove jerry's newly created instance variable salary.
>>>del jerry.salary

# Print class variable salary's value by instance jerry.
>>>print(jerry.salary)
10000

3. Python Class Method.

Python class contain three kind of methods: instance method, static method and class method. Inside the class, use the def keyword to define a method.

3.1 Instance Method.

The instance method of the class is called by the instance, contains at least one self parameter which is the first parameter of the method. When an instance method is executed, the instance calling the method is automatically assigned to the self parameter, self represents an instance of a class, not the class itself. self is not a keyword, but a common name in Python. For example, the print_age(self) method in our previous Worker class is an instance method. Below is an example.

class Worker: 
    
    dept = 'Dev' 
    
    salary = 10000 
    
    def __init__(self, name, age): 
        
        self.name = name 
        
        self.age = age 
        
    def print_age(self): 
        
        print('%s: %s' % (self.name, self.age))
               


if __name__ == '__main__':
    
    tom = Worker("Tom", 90)
    
    tom.print_age()

-------------------------
Tom: 90

3.2 Static Method.

The static method is called by the class and has no default parameters. Remove self from the instance method parameter, and then add @staticmethod above the method definition to create a static method. It belongs to a class, not an instance. It is recommended to use only the calling method of class_name. static_method. (although it can also be called by instance_name.static_method). Below is an example.

class Worker: 
    
    dept = 'Dev' 
    
    salary = 10000 
    
    def __init__(self, name, age): 
        
        self.name = name 
        
        self.age = age 
        
    def print_age(self): 
        
        print('%s: %s' % (self.name, self.age))
        
    @staticmethod
    def static_method():
        print("This is a static method.")


if __name__ == '__main__':
    
    
    Worker.static_method()

---------------------------------

This is a static method.

3.3 Class Method.

Class method is called by class and decorated with @classmethod decorator. At least one cls (referring to class itself, similar to self) parameter is passed in the class method. When a class method is executed, the class calling the method is automatically assigned to the cls parameter. It is recommended to only use class_name.class_method form to call it, although you can call a class method use class_instance.class_method. Below is an example.

class Worker: 
    
    dept = 'Dev' 
    
    salary = 10000 
    
    def __init__(self, name, age): 
        
        self.name = name 
        
        self.age = age 
        
    def print_age(self): 
        
        print('%s: %s' % (self.name, self.age))
        
    @staticmethod
    def static_method():
        print("This is a static method.")
        
    @classmethod    
    def class_method(cls):
        
        print("This is a class method.")
        
        print("Class name is ", cls)    
        
     

if __name__ == '__main__':
    
    Worker.class_method()
----------------------------
This is a class method.
Class name is  <class '__main__.Worker'>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.