- How to Use Static Class Variables in Python
- How to Use Python Static Class Variables?
- How To Access Python Static Class Variables?
- Conclusion
- Статические переменные и методы в Python
- Что такое статическая переменная Python?
- Доступ к статической переменной с использованием того же объекта класса
- Статический метод
- Особенности статических методов
- Использование метода staticmethod()
- Использование декоратора @staticmethod
- Доступ к статическому методу с использованием того же объекта класса
- Функция возвращает значение с помощью статического метода
How to Use Static Class Variables in Python
In Python, we define a static variable inside the class but do not define it at the instance level. The changes we make on static variables at the class level will affect their value in all other class instances. The static variable is used when we do not want to change its value throughout our program.
This article will provide a detailed understanding of Python static class variables and how to use static class variables with multiple examples. The concepts listed below will be elaborated in this tutorial:
Let’s start with the usage:
How to Use Python Static Class Variables?
In Python, we declare class variables when we construct the class. Class variables are unique and shared between all the other objects of the class. We use a class variable when we want the same variables for all class instances. For example, if we want to include the name of a company in the company class, we use a static class variable because the company name is the same for all employees.
Let’s understand the basic concept of static class variables in Python:
class Employee: employee_name = 0 def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname Employee.employee_name += 1 def show(self): print('Employee Name:', self.firstname, self.lastname) print('Total Number of Employees:', type(self).employee_name) s1 = Employee('Alex', 'Henry') s1.show() s2 = Employee('Lily', 'John') s2.show()
- A class name “Employee” is initialized.
- Static Class variable named “employee_name” is initialized within the class.
- The “__Init__”constructor is used to access or define the class’s object and use the class’s attributes to access them and initialize them. Here, we created two attributes named “firstname” and “lastname”
- Self function is defined to show the output of the employee name and the total number of employees present.
- We have changed the value of a class variable using the class name instances.
The above output shows the name of the employees and the total number of employees.
How To Access Python Static Class Variables?
The class name is used to call the static variables in Python. There are also different techniques to access the class variables. Some of them are the following:
- Using Constructor to access the Class Variable
- Using Instance method to access the Class Variable
Example 1: Using Constructor to access the Class Variable
The following lines of code make use of the constructor to access class variables:
class student: school='XYZ School' def __init__(self, name): self.name = name print(self.school) print(student.school) z1 = student('Alex')
- Class named “student” is initialized.
- Class or static variable named “school” is defined inside the class.
- In the “__init__” constructor, we are first accessing the class variable using self as “print(self.school)”. After that, the variable is accessed using the Class name “print(student.school)”.
Note: The object created in the code is necessary to define. Because the attributes of the “__inint__” constructor is initialized using this object.
The above output shows the value of the static variable, accessed using the constructor’s “self” parameter and with the class name directly.
Example 2: Using the Instance method to access the Class Variable
Let’s experience the following code to access the class variable:
class company: company_name ='qtryey' def __init__(self, name, id_no): self.name = name self.id_no = id_no def show(self): print('Using inside instance method') print(self.name, self.id_no, self.company_name) print(company.company_name) z1 = company('Alex', 20) z1.show() print('we can also access from outside the class') print(z1.company_name) print(company.company_name)
- Class name “company” is created.
- Static Variable name “company_name” is created inside the class.
- In the constructor function, we first initialized three attributes named “self”, “name” and “id_no”.
- We define another function named “show()”for calling the static variable.
- The static variable accesses using “self”and “class name”inside the constructor function with an instance method.
- The class variable is accessed from outside of the class using the object reference method with the python statement “print(z1.company_name)” and with the class name “print(company.company_name)”.
In the above output, the static variable is accessed using instance and class name.
That’s all from this guide!
Conclusion
In Python, we use static class variables when we want the same variables among all other class instances. Every class instance can access the static variables through the class name but can not change them. This post defines the methods to create and access the static class variables. For this, we created the static variable inside the class and accessed it using the instance method, the constructor function, and by class name.
TUTORIALS ON LINUX, PROGRAMMING & TECHNOLOGY
Статические переменные и методы в Python
Статическая переменная и статический метод – это широко используемые концепции программирования на различных языках, таких как C ++, PHP, Java и т. l. Эти переменные и методы принадлежат классу и объектам. В этом разделе мы узнаем, как создать статические переменные и методы в Python.
Что такое статическая переменная Python?
Когда мы объявляем переменную внутри класса, но вне метода, она называется статической переменной или переменной класса. Ее можно вызвать непосредственно из класса, но не через экземпляры класса. Однако статические переменные сильно отличаются от других членов и не конфликтуют с тем же именем переменной в программе Python.
Давайте рассмотрим программу, демонстрирующую использование статических переменных в Python.
class Employee: # create Employee class name dept = 'Information technology' # define class variable def __init__(self, name, id): self.name = name # instance variable self.id = id # instance variable # Define the objects of Employee class emp1 = Employee('John', 'E101') emp2 = Employee('Marcus', 'E105') print(emp1.dept) print(emp2.dept) print(emp1.name) print(emp2.name) print(emp1.id) print(emp2.id) # Access class variable using the class name print(Employee.dept) # print the department # change the department of particular instance emp1.dept = 'Networking' print(emp1.dept) print(emp2.dept) # change the department for all instances of the class Employee.dept = 'Database Administration' print(emp1.dept) print(emp2.dept)
Information technology Information technology John Marcus E101 E105 Information technology Networking Information technology Networking Database Administration
В приведенном выше примере dept – это переменная класса, определенная вне методов класса и внутри определения класса. Где имя и идентификатор – это переменная экземпляра, определенная внутри метода.
Доступ к статической переменной с использованием того же объекта класса
Мы можем напрямую обращаться к статической переменной в Python, используя тот же объект класса с оператором точки.
Давайте рассмотрим программу для доступа к статической переменной в Python с использованием того же объекта класса.
class Car: # define the class variable or static variable of class Car num = 7 msg = 'This is a good Car.' # create the object of the class obj = Car() # Access a static variable num using the class name with a dot operator. print("Lucky No.", Car.num) print(Car.msg)
Lucky No. 7 This is a good Car
Статический метод
Python имеет статический метод, принадлежащий классу. Это похоже на статическую переменную, которая привязана к классу, а не к объекту класса. Статический метод можно вызвать без создания объекта для класса.
Это означает, что мы можем напрямую вызвать статический метод со ссылкой на имя класса. Более того, статический метод ограничен классом; следовательно, он не может изменить состояние объекта.
Особенности статических методов
Ниже приведены особенности статического метода:
- Статический метод в Python связан с классом.
- Его можно вызвать непосредственно из класса по ссылке на имя класса.
- Он не может получить доступ к атрибутам класса в программе Python.
- Привязан только к классу. Таким образом, он не может изменить состояние объекта.
- Он также используется для разделения служебных методов для класса.
- Может быть определен только внутри класса, но не для объектов класса.
- Все объекты класса используют только одну копию статического метода.
Есть два способа определить статический метод в Python:
Использование метода staticmethod()
Staticmethod() – это встроенная функция в Python, которая используется для возврата заданной функции как статического метода.
Staticmethod() принимает единственный параметр. Где переданный параметр – это функция, которую необходимо преобразовать в статический метод.
Давайте рассмотрим программу для создания функции как статического метода с использованием staticmethod() в Python.
class Marks: def Math_num(a, b): # define the static Math_num() function return a + b def Sci_num(a, b): # define the static Sci_num() function return a +b def Eng_num(a, b): # define the static Eng_num() function return a +b # create Math_num as static method Marks.Math_num = staticmethod(Marks.Math_num) # print the total marks in Maths print(" Total Marks in Maths" , Marks.Math_num(64, 28)) # create Sci_num as static method Marks.Sci_num = staticmethod(Marks.Sci_num) # print the total marks in Science print(" Total Marks in Science" , Marks.Sci_num(70, 25)) # create Eng_num as static method Marks.Eng_num = staticmethod(Marks.Eng_num) # print the total marks in English print(" Total Marks in English" , Marks.Eng_num(65, 30))
Total Marks in Maths 92 Total Marks in Science 95 Total Marks in English 95
В приведенной выше программе мы объявили метод Math_num, метод Sci_num и метод Eng_num как статический метод вне класса с помощью функции staticmethod(). После этого мы можем вызвать статический метод напрямую, используя имя класса Marks.
Использование декоратора @staticmethod
@Staticmethod – это встроенный декоратор, который определяет статический метод внутри класса. Он не получает никаких аргументов в качестве ссылки на экземпляр класса или класс, вызывающий сам статический метод.
class Abc: @staticmethod def function_name(arg1, arg2, ?): # Statement to be executed Returns: a static method for function function_name
Примечание. @Staticmethod – это современный подход к определению метода как статического, и большая часть программистов использует этот подход в программировании на Python.
Давайте создадим программу для определения статического метода с помощью декоратора @staticmethod в Python.
class Marks: @staticmethod def Math_num(a, b): # define the static Math_num() function return a + b @staticmethod def Sci_num(a, b): # define the static Sci_num() function return a +b @staticmethod def Eng_num(a, b): # define the static Eng_num() function return a +b # print the total marks in Maths print(" Total Marks in Maths" , Marks.Math_num(64, 28)) # print the total marks in Science print(" Total Marks in Science" , Marks.Sci_num(70, 25)) # print the total marks in English print(" Total Marks in English" , Marks.Eng_num(65, 30))
Total Marks in Maths 92 Total Marks in Science 95 Total Marks in English 95
Доступ к статическому методу с использованием того же объекта класса
Рассмотрим программу для доступа к статическому методу класса с помощью @staticmethod в Python.
class Test: # define a static method using the @staticmethod decorator in Python. @staticmethod def beg(): print("Welcome to the World!! ") # create an object of the class Test obj = Test() # call the static method obj.beg()
Функция возвращает значение с помощью статического метода
Напишем программу для возврата значения с помощью метода @static в Python.
class Person: @staticmethod def Age (age): if (ageThe person is not eligible to vote.