Python staticmethod and classmethod core features brief overview
Sometimes, programs need to process data associated with classes instead of instances. Consider keeping track of the number of instances created from a class, or maintaining a list of all of a class’s instances that are currently in memory. This type of information and its processing are associated with the class rather than its instances. That is, the information is usually stored on the class itself and processed in the absence of any instance.
Documentation
Fixture
Data model
In order to illustrate the core idea of these built-in functions lets create a incidental but lucid code snippet:
Mock-up objects creation
Test the classes’ properties
Result analysis
Obviously that we’ve created three Car objects but our code identified and counted them as Vehicles . Lets try to increment the particular counter in a straightforward manner:
In Python 3.*, we need not declare such methods as static if they will be called through a class only, but we must do so in order to call them through an instance.
Conclusion
Both staticmethod and classmethod
can be called without the instance
self instance argument not passes to them
staticmethod
simple functions with no self argument that are nested in a class and are designed to work on class attributes instead of instance attributes. Static methods never receive an automatic self argument, whether called through a class or an instance. They usually keep track of information that spans all instances, rather than providing behavior for instances.
classmethod
methods of a class that are passed a class object in their first argument instead of an instance, regardless of whether they are called through an instance or a class. Such methods can access class data through their self class argument even if called through an instance. Normal methods (now known in formal circles as instance methods) still receive a subject instance when called; static and class methods do not.
Rukovodstvo
статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.
Объяснение @classmethod и @staticmethod Python
Python — уникальный язык в том смысле, что его довольно легко выучить, учитывая его простой синтаксис, но при этом он чрезвычайно мощный. Под капотом гораздо больше функций, чем вы можете себе представить. Хотя в этом утверждении я мог бы иметь в виду довольно много разных вещей, в данном случае я говорю о декораторах [https://wiki.python.org/moin/PythonDecorators] @classmethod и @staticmethod. Для многих ваших проектов вам, вероятно, не понадобились или вы не сталкивались с этими функциями, но вы можете
Время чтения: 4 мин.
Python — уникальный язык в том смысле, что его довольно легко выучить, учитывая его простой синтаксис, но при этом он чрезвычайно мощный. Под капотом гораздо больше функций, чем вы можете себе представить. Хотя в этом утверждении я мог бы иметь в виду довольно много разных вещей, в данном случае я говорю о декораторах @classmethod и @staticmethod . Для многих ваших проектов вам, вероятно, не нужны эти функции и вы не сталкивались с ними, но вы можете обнаружить, что они пригодятся гораздо больше, чем вы ожидаете. Не так очевидно, как создавать статические методы Python, и здесь на помощь приходят эти два декоратора.
В этой статье я расскажу вам, что делает каждый из этих декораторов, их отличия и несколько примеров каждого из них.
Декоратор @classmethod
Этот декоратор существует, поэтому вы можете создавать методы класса, которым передается фактический объект класса в вызове функции, так же, как self передается любому другому обычному методу экземпляра в классе.
В этих методах экземпляра self — это сам объект экземпляра класса, который затем может использоваться для обработки данных экземпляра. @classmethod также имеют обязательный первый аргумент, но этот аргумент не является экземпляром класса, это фактически сам неустановленный класс. Итак, хотя типичный метод класса может выглядеть так:
@classmethod этого можно использовать аналогичный метод @classmethod:
Это очень хорошо следует статическому шаблону фабрики , инкапсулируя логику синтаксического анализа внутри самого метода.
Приведенный выше пример очень простой, но вы можете представить более сложные примеры, которые сделают его более привлекательным. Представьте, что Student можно сериализовать во многих различных форматах. Вы можете использовать ту же стратегию, чтобы проанализировать их все:
Декоратор становится еще более полезным, когда вы понимаете его полезность в подклассах. Поскольку объект класса предоставляется вам внутри метода, вы все равно можете использовать тот же @classmethod для подклассов.
Декоратор @staticmethod
@staticmethod похож на @classmethod в том, что он может быть вызван из неустановленного объекта класса, хотя в этом случае его методу cls Пример может выглядеть так:
Поскольку self не передается, это означает, что у нас также нет доступа к каким-либо данным экземпляра, и, следовательно, этот метод также не может быть вызван для созданного объекта.
Эти типы методов обычно не предназначены для создания / инстанцирования объектов, но они могут содержать некоторый тип логики, относящийся к самому классу, например вспомогательный или служебный метод.
@classmethod против @staticmethod
Самым очевидным отличием этих декораторов является их способность создавать статические методы внутри класса. Эти типы методов могут вызываться для неустановленных объектов класса, подобно классам, использующим static в Java.
На самом деле между этими двумя декораторами методов есть только одно различие, но оно очень важное. Вы, наверное, заметили в разделах выше, что методы @classmethod cls отправляемый их методам, а @staticmethod — нет.
Этот cls — это объект класса, о котором мы говорили, который позволяет @classmethod легко создавать экземпляры класса независимо от происходящего наследования. Отсутствие этого параметра cls @staticmethod делает их настоящими статическими методами в традиционном смысле. Их основная цель — содержать логику, относящуюся к классу, но эта логика не должна нуждаться в конкретных данных экземпляра класса.
Более длинный пример
Теперь давайте посмотрим на другой пример, в котором мы используем оба типа вместе в одном классе:
Обратите внимание, как статические методы могут даже работать вместе с вызовом from_csv validate с использованием объекта cls При выполнении приведенного выше кода должен быть распечатан массив действительных оценок, а со второй попытки произойдет сбой, в результате чего будет выведено «Недействительно!».
Заключение
В этой статье вы увидели, как @classmethod и @staticmethod работают в Python, некоторые примеры каждого из них в действии и чем они отличаются друг от друга. Надеюсь, теперь вы можете применить их к своим собственным проектам и использовать их для дальнейшего улучшения качества и организации вашего собственного кода.
Вы когда-нибудь использовали эти декораторы раньше, и если да, то как? Дайте нам знать об этом в комментариях!
Python classmethod и staticmethod зачем нужны
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python.
What is Class Method in Python?
The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as an implicit first argument, just like an instance method receives the instance
Syntax Python Class Method:
- A class method is a method that is bound to the class and not the object of the class.
- They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
- It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that will be applicable to all the instances.
What is the Static Method in Python?
A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.
Syntax Python Static Method:
Class method vs Static Method
The difference between the Class method and the static method is:
- A class method takes cls as the first parameter while a static method needs no specific parameters.
- A class method can access or modify the class state while a static method can’t access or modify it.
- In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
- We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.
When to use the class or static method?
- We generally use the class method to create factory methods. Factory methods return class objects ( similar to a constructor ) for different use cases.
- We generally use static methods to create utility functions.
How to define a class method and a static method?
To define a class method in python, we use @classmethod decorator, and to define a static method we use @staticmethod decorator.
Let us look at an example to understand the difference between both of them. Let us say we want to create a class Person. Now, python doesn’t support method overloading like C++ or Java so we use class methods to create factory methods. In the below example we use a class method to create a person object from birth year.
As explained above we use static methods to create utility functions. In the below example we use a static method to check if a person is an adult or not.
@classmethod vs. @staticmethod in Python
Something that unavoidably ends up coming up when learning Python is this issue of classmethods and staticmethods, especially for students coming from a Java background, where there are no classmethods.
In Python, we can define these using their respective decorators. Below a not-very-useful example which nevertheless illustrates what they look like:
The only difference between @classmethod and @staticmethod is that in the @classmethod, the class is bound to the method as the first argument (cls). This means that it is easy to access the class, in the method, via the cls argument, instead of having to use the full class name.
So in the case of our sum(cls, value1, value2) method, the cls argument would be the Number class, which is the class in which the method lives.
But you may say: “it makes sense, but adds another bit of complexity that isn’t necessary, as we could just use the class name?”
Lets do that instead, and not use @classmethod, and see what happens…
And this works, except when we use inheritance. In inheritance, a sub-class (also known as child class) inherits the methods of the parent class.
If we created a sub-class of Number, it would contain all of the Number methods, and it could also define more methods of its own.
So now we could call methods like so:
However, if we call the Float.sum() method, bad things start to happen…
The Float.sum(value1, value2) method is actually returning a Number instance, and not a Float instance.
So our variable f is actually not a Float, it is a Number. When we call f.print() we are calling the print() method from the Number class, and not the one we overwrote in our Float class.
The solution is to go back to using @classmethod. That way, we use cls instead of Number, and cls always refers to the class that we are calling from. If we use Number.sum(10, 15), we would get back a Number instance. If we use Float.sum(15.474, 19.232), we would get back a Float instance.
So when should you use @staticmethod?
Only use @staticmethod when you want to place a method inside a class that is logically related to the class, but does not necessarily interact with any specific instance.
For example, I would use static methods when defining a database layer. I would define a Database class which has a few static methods to insert or find data from the database. At no point am I creating Database instances that contain that data, but the methods to find and insert are related to a Database.