- Статические переменные и методы в Python
- Что такое статическая переменная Python?
- Доступ к статической переменной с использованием того же объекта класса
- Статический метод
- Особенности статических методов
- Использование метода staticmethod()
- Использование декоратора @staticmethod
- Доступ к статическому методу с использованием того же объекта класса
- Функция возвращает значение с помощью статического метода
- Python static method
- Python static method
- What is a static method?
- Creating python static methods
- Using staticmethod()
- Using @staticmethod
- Advantages of Python static method
Статические переменные и методы в 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.Python static method
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python static method
In this quick post, we will learn how to create and use a Python static method. We will also have a look at what advantages and disadvantages static methods offer as compared to the instance methods. Let’s get started.
What is a static method?
Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. This also means that static methods cannot modify the state of an object as they are not bound to it. Let’s see how we can create static methods in Python.
Creating python static methods
Using staticmethod()
class Calculator: def addNumbers(x, y): return x + y # create addNumbers static method Calculator.addNumbers = staticmethod(Calculator.addNumbers) print('Product:', Calculator.addNumbers(15, 110))
Note that we called the addNumbers we created without an object. When we run this program, here is the output we will get: There were no surprises there. This approach is controlled as at each place, it is possible to create a static method out of a class method as well. Let’s see another approach with the same example here.
Using @staticmethod
This is a more subtle way of creating a Static method as we do not have to rely on a statement definition of a method being a class method and making it static at each place you make it static. Let’s use this annotation in a code snippet:
class Calculator: # create addNumbers static method @staticmethod def addNumbers(x, y): return x + y print('Product:', Calculator.addNumbers(15, 110))
When we run this program, here is the output we will get: This was actually a much better way to create a static method as the intention of keeping the method static is clear as soon as we create it and mark it with the @staticmethod annotation.
Advantages of Python static method
Static methods have a very clear use-case. When we need some functionality not w.r.t an Object but w.r.t the complete class, we make a method static. This is pretty much advantageous when we need to create Utility methods as they aren’t tied to an object lifecycle usually. Finally, note that in a static method, we don’t need the self to be passed as the first argument. API Reference: Python Documentation
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us