Python static variables in methods

Статические переменные и методы в 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 имеет статический метод, принадлежащий классу. Это похоже на статическую переменную, которая привязана к классу, а не к объекту класса. Статический метод можно вызвать без создания объекта для класса.

Это означает, что мы можем напрямую вызвать статический метод со ссылкой на имя класса. Более того, статический метод ограничен классом; следовательно, он не может изменить состояние объекта.

Особенности статических методов

Ниже приведены особенности статического метода:

  1. Статический метод в Python связан с классом.
  2. Его можно вызвать непосредственно из класса по ссылке на имя класса.
  3. Он не может получить доступ к атрибутам класса в программе Python.
  4. Привязан только к классу. Таким образом, он не может изменить состояние объекта.
  5. Он также используется для разделения служебных методов для класса.
  6. Может быть определен только внутри класса, но не для объектов класса.
  7. Все объекты класса используют только одну копию статического метода.

Есть два способа определить статический метод в 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 (age 
The person is not eligible to vote.

Источник

Python Static Variable And Its Methods

python static variable

Hello geeks and welcome in this article, we will cover Python static variable. Along with that, we will also look at its importance and definition. For an overall better understanding, we will also look at a couple of examples. In general, static means something stationary.

Now with that said, let us try to understand it in general terms. We can understand the Python static variable as a variable present in the class it is defined in. It is also called a class variable because all the objects share it. As we further move ahead in this article, we will look at how it is defined and different ways to access it.

Defining A Python Static Variable

In this section, we will play emphasis on defining the static variable. We will look at the general syntax and other things to pay attention to.

#input class lang: c="low level" p="high level"

Above we can see the very basic deceleration using the Static variable. In general, the syntax goes class name: and then followed by the variable declaration. Here we named it as the class as lang and then defined our variables.

Now let us look at a bit more advanced declaration.

class lang: def __init__(self,lev,year): self.lev = lev self.year = year #objects c = lang('low-level', 1972) p = lang('high-level', 1991)

Here in the above example, we can see that we have carried on from the first example. But instead of declaring a simple variable, we have used an object for declaring it. Now since we are done with the declaration part now we will try to access the declared variable.

Accessing A Python Static Variable

In this section, our main focus is to access the defined variables. Trust me there are several methods available to us for performing this operation. We will look at each one of them one by one.

1. Direct Method

The direct method allows us to access the variable directly by using the defined class name and the dot operator. It is one of the simplest and the most convenient method to access the static variable. Let’s see this in action.

class lang: c="low level" p="high level" print(lang.c) print(lang.p)

See how easily we were able to access our value stored using this method.

2. Object Method

In this example, we are going to use the object method to access the stored variable. This method is beneficial when dealing with data on a large scale.

class lang: c="low level" p="high level" ob=lang() print(ob.p) print(ob.c)
#output high level low level

Here we can see that our output doesn’t change, and we can create an object by just using a single line of code. In the second example that we discussed while talking about declaring the variable also has the object associated with now, let us try to access its elements.

class lang: def __init__(self,lev,year): self.lev = lev self.year = year #objects c = lang('low-level', 1972) p = lang('high-level', 1991) print(c.lev,c.year) print(p.lev,p.year)
#output low-level 1972 high-level 1991

Here above, we can see how we have declared the objects for 2 of our variables and how we accessed them using the object method. These are the methods that we generally use for accessing the object. You can use anyone at your convenience. The one thing you should keep in mind is never trying to access the variable directly. Like this “print(c)” (concerning our example), in that case, you get nothing more than the error.

3. Python Static Variable in a Function

You can declare a static variable by using the function. But you have to add this with a try-except block to initialize the variable on the first call. The following example will help you understand –

def foo(): try: foo.counter += 1 except AttributeError: foo.counter = 1 print("Counter is %d" % foo.counter) foo() foo() foo()
Counter is 1 Counter is 2 Counter is 3

Must Read

Conclusion

In this article, we read about Python static Variables. We looked at different methods for defining and accessing the variable through examples. In the end, we can conclude that a variable that is present in the class it is defined in is called Python static variable. I hope this article was able to clear all of your doubts. In case you have any unsolved queries feel free to write them below in the comment section. Done reading this, why not read NumPy Variance next.

Источник

Оцените статью