How To Declare A Static Variable In A Function In Python?

This tutorial is about how to Declare a Static Variable in a Function in Python. First, we need to understand static variables and how they work. Static variables are declared at the beginning of your code block. These variables don’t change after they are declared and before they are defined or assigned another value. In other words, they are global variables because they can be accessed anywhere in your code, and their values will never change unless you change them.

A static variable is a variable that can be modified or changed in its value. In other words, we cannot alter them after assigning them the value during the declaration. Here are some of the most prevalent ways to declare a static variable in a function in Python or access a static variable in Python.

  • Defining Static Variable Outside the Function 
  • Declaring static variables within the function using the constructor and instance approach 
  • A static variable is declared in a function by setting an Attribute
  • Using the hasattr() method to declare a static variable in a function in Python
  • Using hasattr() method in __init__() ( a class constructor) to declare a static variable in a function in Python
  • Declaring the Static variable within a Class to declare a static variable in a function in Python
  • Using the hasattr() method inside a method to declare a static variable in a function in Python
  • Using a Class Object with static variable using the (.) operator to declare a static variable in a function in Python
  • Using the type() method to declare a static variable in a function in Python
  • Using the __class__ method to declare a static variable in a function in Python

*Working on Jupyter notebook Anaconda Environment. 

1) Defining Static Variable Outside the Function 

The Execution process executes in the following sequence to declare a static variable in a function in Python:

  • Defining a class, “url”, inject “:” after creating a class name to justify Pythonic script.
  • Then define two static class variables with their values,  host_name= ‘Entechin’ and   domain = ‘.com’
  • After defining a static variable, describe a method, website(self). A static variable, host_name, and a static variable, domain, are printed within this method.
  • They are then printing the static variable of the person_name class. 
  • After that, an object for the “url” class is defined to call the website() method and print them.

Here is the source code for declaring a static variable in a function in Python. 

class url: 
    host_name= 'Entechin'
    domain = '.com'
    def website(self):
        print(url.host_name)
        print(url.domain)
        return url.host_name + url.domain
print("Host_name :", url.host_name)
print("Domain :", url.domain)
Host_name : Entechin
Domain : .com

Creating a ‘url’ class object, “site,” to print the url.

site = url()
print("\nurl :", site.website())
Entechin
.com

url : Entechin.com

2) Declaring static variables within the function using the constructor and instance approach 

__init__ is a constructor in object-oriented concepts and one of the methods in Python classes. However, In this method, the class initializes the object’s attributes on creation.

The self represents instances of the class. Python’s “self” keyword allows us to access the class’s attributes and methods.

  • When we define a function, the first parameter passed is self, and the other attributes are passed as argument.
  • Here the self-parameter allows us to access the attributes of the function.
  • The first thing we do is define a class, person(object), and passing object as an argument.
  • host, domain, niche will be an Instance variable created inside the constructor. 
  • If the variable didn’t create before, create a method called website that will make a static variable and return the value when some mathematical operation is applied.
  • In the next step, call the url class and pass the static variable values within it. However, It saves the static variable values in the class object (site=url(‘Entechin’,’.com’, ‘learning platform’)). It will return the full URL of a ‘url’ class in this case.

Source code to declare a static variable in a function in python using instance and constructor methods. 

class url(object):
    def __init__(self, host, domain, niche):
        self.host = host
        self.domain = domain
        self.niche = niche
    
    def website(self):
        return self.host + ' ' + self.domain
site=url('Entechin','.com', 'learning platform')
print("host_name :", site.host)
print("domain :", site.domain)
print("niche :", site.niche)
print("url :", site.website())
host_name : Entechin
domain : .com
niche : learning platform
url : Entechin .com

3) A STATIC VARIABLE IS DEFINED IN A FUNCTION BY SETTING AN ATTRIBUTE

Declaring a static variable in a function in Python is done by setting an object attribute in a function. 

Here is how it executes!

  • Define a function
  • Invoke an add operator with entechin.i. 
  • Use a variable entechin.i, where entechin is the function’s name and “i” is the name of a variable as a static variable in entechin. 
  • The function returns the counter by computing the operator operation. 
  • A static variable is declared 0; the counter takes the set static variable value and returns the counter. 
  • Firstly, it returns 1 (0+1=1), and when the second-time static variable invokes, it returns 2 (1+1=2), and so on. 
def entechin():
   entechin.i += 1
   return entechin.i
entechin.i = 0
static_variable_01 = entechin()
print(static_variable_01)
static_variable_02 = entechin()
print(static_variable_02)
1
2

4) Using the hasattr() method to declare a static variable in a function in Python

Call hasattr(fun, var) in the function to validate that entechin.i  has been initialized. You should initialize it if it hasn’t already. However, proceed as usual.

However, In the following example,  not hasattr check either function entechin has attribute “i” or not. 

def entechin():
   if not hasattr(entechin, "i"):
        entechin.i = 0
   entechin.i += 1
   return entechin.i
static_variable_01 = entechin()
print(static_variable_01)
static_variable_02 = entechin()
print(static_variable_02)
1
2

5) Using hasattr() method in __init__() ( a class constructor)

In the constructor, use the hasattr() method to check for class variables (static variables). However, the syntax will be:

boat.width (class.static_variable)  
boat.depth = 3    

The execution of declaring a static variable in a function in Python is demonstrated in the following example as:

  • Declaring a class
  • Declaring a constructor, taking length and size as a parameter
  • ‘’self'(itself a class_object) is passed to each method
  • Invoke, not hasattr, to Check whether a class boat has attribute width or not
  • Define a class variable
  • After that, define an instance variable using self(a class object) with the (.) operator.
  • Now print the size( a constructor parameter)
  • Now create a class object for class “boat” and pass object attributes within its scope.
  • Remember, an attribute must be of str data type due to the concatenation restriction we used in our case. 
  • This will print the declared object attribute values defined in a class object. 
#considering a class "boat"
class boat:
    
    #Declaring a constructor, taking length and size as a parameter
    # 'self'(itself a class_object) is passed to each method
    def __init__(self, length, size):
        
        #Checking whether a class boat has attribute width or not
        if not hasattr(boat, 'width'):
                    #considering a class or static_variable

            boat.width = 3  
        if not hasattr(boat, 'depth'):
                    #considering a class or static_variable

            boat.depth = 3    
            
        self.length = length
        self.size = size
        print('The boat has a depth of ' + size )

#Creating a class object 
class_object_01 = boat(6, '25')
class_object_02 = boat(3, '3')
The boat has depth of 25
The boat has depth of 3

6) Declaring the Static Variable Within A Class

Declaring a static variable in a class but not within a method can be the most accessible approach to accessing static or class variables. 

The syntax will be:

class boat:
   height = 3
   depth = 3

The execution of declaring a static variable in a function in Python is demonstrated in the following example as:

  • Declaring a class
  • Declare a static variable in a class
  • Declaring a constructor, taking length and size as a parameter
  • ‘’self'(itself a class_object) is passed to each method
  •  Length and size are variable attributes in an instance or instance attributes belonging to the class boat.
  • After that, define an instance variable using self(a class object) with the (.) operator.
  • Now print the size( a constructor parameter)
  • Now create a class object for class “boat” and pass object attributes within its scope.
  • In our example, we used concatenation, which requires a string data type for attributes. 
  • This will print the instance variable values defined in a class object. 
#considering a class "boat"
class boat:
     #considering a class or static_variable
   height = 3
   depth = 3
   #Declaring a constructor, taking length and size as a parameter
    # 'self'(itself a class_object) is passed to each method
   def __init__(self, length, size):
       self.length = length
       self.size = size
       print('The boat has size of ' + size )
#Creating a class object
class_object_01 = boat(3, '6')
class_object_02 = boat(3, '3')
The boat has size of 6
The boat has size of 3

7) Using the hasattr() method inside a method

Declaring a static variable in a function in python uses the hasattr() method inside a method. Therefore, using the hasattr() method, we can declare the static or class variable within the defined static_method()method. 

The syntax will be as follows:

 def static_method(self):
        #using hasattr() method
        if not hasattr(boat, 'size'): 
      #considering a class or static_variable
            boat.color = 'White'
    
#Creating a class object 
class_object_01 = boat(3, '6')

class_object_01.static_method()
#access color (a ststic variable) using class object
print(class_object_01.color) 

The execution of declaring a static variable in a function in Python can be accomplished as:

  • Declaring a class
  • Declaring a constructor will create a variable named length and size as a parameter
  • ‘’self'(itself a class_object) within class’s constructor (__init__).  is passed to each method.
  • Printing the size( a constructor parameter)
  • Now declare a method
  • In a method using the hasattr() function, declare a static variable. 
  • Now create a class object for class “boat” and pass object attributes within its scope.
  • Furthermore, using the dot operator,  invoke class object with define function(static_method())
  • Lastly, print the declared class variable or static variable values defined within the method. Access the static variable (declared in the static_method()) using the dot(.) operator with the class object. 
#considering a class "boat"
class boat:
    #Declaring a constructor, taking length and size as a parameter
    #Remember 'self'(itself a class_object) is passed to each method
    def __init__(self, length, size):
        self.length = length
        self.size = size
        print('The boat has size of ' + size )
        
        #Using method to declare a static variable
    def static_method(self):
        #using hasattr() method
        if not hasattr(boat, 'color'): 
      #considering a class or static_variable
            boat.color = 'White'    

#Creating a class object 
class_object_01 = boat(3, '6')

class_object_01.static_method()
#access color (a static variable) using the class object
print(class_object_01.color)  
The boat has size of 6
White

8) Using a Class Object with static variable using (.) operator 

Invoking a static variable using a class object with a (.) operator allows us to access a static variable in a function in python. 

However, the execution process to declare a static variable in a function in python is demonstrated in the following example:

  • Considering a class
  • Declare static variables
  • Declaring a constructor will create a variable named length and size as a parameter.
  • ‘’self'(itself a class_object) within class’s constructor (__init__).  is passed to each method.
  • Create a class object for class instances variables and pass object attributes to it.
  • Now print static variables values using a class object with define a static variable using the (.) operator. 
#considering a class "boat"
class boat:
     #considering a class or static_variable
   height = 25
   depth = 3
   #Declaring a constructor, taking length and size as a parameter
   #Remember 'self'(itself a class_object) is passed to each method
   def __init__(self, length, size):
       self.length = length
       self.size = size
#Creating a class object
class_object_01 = boat(3, '6')
class_object_02 = boat(3, '3')
#calling the static variables using class instances
print(class_object_01.height)
print(class_object_02.depth)
25
3

9) Using the type() method

As a result of the arguments passed to type(), a new type object will be returned, or the type() function will return the type of the object itself. However, The type() function is used in the following example to access a static variable in the Python code. 

The syntax will be as follows: 

print("depth of boat: ", type(class_object_01).depth)

The execution process to declare a static variable in a function in python is demonstrated in the following example:

  • Considering a class
  • Declare static variables
  • Declaring a constructor will create a variable named length and size as a parameter.
  • ‘’self'(itself a class_object) within class’s constructor (__init__),  is passed to each method.
  • Create a class object for class instance variables and pass object attributes to it.
  • Now print static variables values using a class object with a defined static variable using the (.) operator. 
  • Print the static variables using the type () function by passing an argument to it. The argument will be the class object. And while syntax will be followed as a type() function, an argument passed to it, and the static variable with the (.) operator.
#considering a class "boat"
class boat:

      #considering a class or static_variable
    height = 25
    depth = 3
    #Declaring a constructor, taking length and size as a parameter
    #Remember 'self'(itself a class_object) is passed to each method
    def __init__(self, length, size):
        self.length = length
        self.size = size
        print('The boat has size of ' + size )

#Creating a class object 
class_object_01 = boat(3, '6')

#calling the static variables using class instances
print(class_object_01.height)
print(class_object_02.depth)

#Using the type() method
print('Height of boat: ', class_object_01.height )
print("depth of boat: ", type(class_object_01).depth)
The boat has size of 6
25
3
Height of boat:  25
depth of boat:  3

10) Using the __class__ method

Class, type, function, method, or instance names are printed by __class__ method built-in attribute. However, Here it is used to declare and access a static variable in a function in python. 

There is the execution process:

  • Considering a class
  • Declare static variables, height, and depth. 
  • Declaring a constructor will create a variable named length and size as a parameter.
  • ‘’self'(itself a class_object) within class’s constructor (__init__),  is passed to each method.
  • Create a class object for class instance variables and pass object attributes to it.
  • Now print static variables values using a class object with a defined static variable using the (.) operator. 
  • Print the static variables using the class object with a __class__ method and the defined static variable with the (.) operator. 
#considering a class "boat"
class boat:

      #considering a class or static_variable
    height = 25
    depth = 3
    #Declaring a constructor, taking size and length as a parameter
    #Remember 'self'(itself a class_object) is passed to each method
    def __init__(self, length, size):
        self.length = length
        self.size = size
        print('The boat has a size ' + size )

#Creating a class object 
class_object_01 = boat(3, '6')

#calling the static variables using class instances
print(class_object_01.height)
print(class_object_02.depth)

#calling the static variables using __class__ method with (.) operator
print('height of boat: ', class_object_01.__class__.height)
print('depth of boat: ', class_object_01.__class__.depth)
The boat has a size 6
25
3
height of boat:  25
depth of boat:  3

Conclusion

There are many different ways you can use variables in Python. However, You can declare them outside of functions, or you can also use the constructor and instance, allowing you to keep track of them by name. Furthermore, these methods for declaring a static variable in a function in Python are discussed. 

If you want to learn more about Python Programming, visit Python Programming Tutorials.

Leave a Comment

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