Static functions in Python
static function (Static Method)A function that can be accessed directly from the class that contains it without having to create an object from it.
So the main idea of defining a function as a static function is to make the function callable directly from the class inside it.
The most important thing to know is that static functions are designed to work with classes placed in them in general and not with objects created from that class in particular.
Also, even if static functions are called from an object of this class, this function will not be treated specifically for the object, but it will remain as if you are calling it directly from the class. Since static functions are not designed to handle objects specifically, this is why the word can never be placed selfinside a static function.
Conditions for defining a static function in Python
A static function is defined just like any normal function with the word placed
@staticmethodover it as an indication that it is a static function.It is forbidden to put the word
selfin it because this word is mainly used to access variables set as properties for the objects to be created from the class.To access any variable in the class from the constant function, we write the name of the class, then put a dot, and then put the name of the variable.
Don't worry if you don't understand everything mentioned so far because you will understand everything later from the examples.
Comprehensive examples of static functions in Python
In the following example, we have defined a class whose name StaticExamplewe put in it a constant function whose name is print_msg()interested in only printing a regular sentence.
First example using static functions in Python
# StaticExample Here we have defined the class
class StaticExample:
# Here we have defined a constant function in the class that when called, it prints only a regular sentence
@staticmethod
def print_msg():
print("Static method can be called directly from the class.")
# So that we can deal with it StaticExample here we have included the class from StaticExample import StaticExample # Without having to create an object from StaticExample directly from the print_msg() class here we called the static function StaticExample.print_msg()
• We will get the following result when we run the fileTest.
In the following example, we have defined a class called Sessionand put 4 variables in it( title- language- teacher- credits)And a constant function whose name is print_info()interested in only printing the values of these variables in an ordered manner.
Second example using static functions in Python
# Session Here we have defined the class
class session:
# Here we put 4 variables (ie properties) in the class
title = 'Python for beginners'
language = 'English'
teacher = 'Sara Smith'
credits = 5
# Here we have defined a static function in the class that when called, prints the property values in an orderly manner
# Note that you are forced to put the name of the class, then a period, and then the name of the variable you want to access from inside the function
@staticmethod
def print_info():
print('Title:', Session.title)
print('Language:', Session.language)
print('Teacher:', Session.teacher)
print('Credits Number:', Session.credits)
# So that we can deal with it Session here we have included the class from Session import Session # Session directly from the print_info() class here we called the static function Session.print_info()
• We will get the following result when we run the fileTest.
Language: English
Teacher: Sara Smith
Credit Number: 5
In the following example, we have defined a class whose name MyToolswe put in it a fixed function whose name is print_words_count()intended to print the number of words in the text that we pass to it when it is called.
Third example using static functions in Python
# MyTools Here we have defined the class
class MyTools:
# It contains one parameter print_words_count Here we have defined a constant function named
@staticmethod
def print_words_count(val):
# Here we said if the value we passed to it is a text value
if isinstance(val, str):
# If this text value is empty text, it will print that the text is empty text and the number of words in it is zero
if val == '':
print('Empty string, so number of words is 0')
# and then print the value of words_count if this text value is not empty text then the number of words in it will be stored in the variable
else:
words_count = len(val.split())
print('Number of words is:', words_count)
# is a text value The next sentence val will be printed if the parameter value is not
else:
print('Oops..', val, 'is not a string!')
# So that we can deal with it MyTools here we have included the class from MyTools import MyTools # Here we have defined a text variable containing a set of words text = 'Today, you are studying static methods.' # text to find out how many words are in the variable MyTools from the class print_words_count() here we called the static function MyTools.print_words_count(text)
• We will get the following result when we run the fileTest.
The following example proves to you that if a static function is called from an object of the class it is in, this function will not be treated exclusively for the object. That is, whether you call it from the object or from the class, you will get the same result, noting that it is always preferable to call the static function directly from the class in it and not from an object from it.
Fourth example of using static functions in Python
# StaticExample Here we have defined the class
class StaticExample:
# Here we have defined a variable (any property) in the class and determined that its value is 5
x = 5
# located directly in the class and not in an object of it x displays the value of the variable print_x here we have defined a static function named
@staticmethod
def print_x():
print('StaticExample.x =', StaticExample.x)
# So that we can access the function in it and create an object from it as well StaticExample here we have included the class
from StaticExample import StaticExample
# obj named StaticExample Here we created an object from the class
obj = StaticExample()
# From 5 to 10 obj of object x here we have changed the value of
obj.x = 10
# of the object which is equal to 10 x of the class, i.e. 5 and not the value of x Note that the .obj value will be printed from the object print_x() here we called the static function
obj.print_x()
# of class x directly, so the value of StaticExample will also be printed from class print_x() here we called the static function
StaticExample.print_x() # of the class because we are calling the static function directly from the class
# print_x() is to be called from it like this and not via the obj static function of object x the only way to print a value
print('obj.x =', obj.x)
• We will get the following result when we run the fileTest.
StaticExample.x = 5
obj.x = 10