The difference between a Python static method and a class method

Source: Internet
Author: User
Tags date1 instance method time zones parse string python static method

Python Staticmethod and Classmethod

Though Classmethod and Staticmethod is quite similar, there ' s a slight difference in usage for both Entities:classmethod Must has a reference to a class object as the first parameter, whereas Staticmethod can has no parameters at all.

Let's look at all that is said in real examples.

Although Classmethod and Staticmethod are very similar, there are still some obvious differences in usage. Classmethod must have a reference to the class object as the first argument, and Staticmethod can have no arguments.

Let's look at a few examples.

Example –boilerplate

Let's assume an example of a class, the dealing with date information (this is what would be we boilerplate to cook on):

Python
123456 class Date(object):     def __init__ (self,< Span class= "crayon-h" > day=0, month= 0, year=0) : Self . Day = DaySelf . Month = month Self . Year = Year

This class obviously could is used to the store information about certain dates (without timezone information; let's assume Al L dates is presented in UTC).

It is clear that objects of this class can store date information (not including time zones, assuming they are all stored in UTC).

Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemeth OD, have the first non-optional argument (self) that holds reference to a newly created instance.

The init method Here is used to initialize the object's properties, and its first argument must be self, which points to the object that has already been created.

Class Method

We have the some tasks that can is nicely done using classmethods.

Let's assume that we want to create a lot of date class instances have date information coming from outer source encoded As a string of next format (' dd-mm-yyyy '). We have the different places of our source code in project.

There are some great things you can do with Classmethod.

For example, we can support the creation of an object from a date string in a particular format, which is in the format (' dd-mm-yyyy '). Obviously, we can only do this in other places rather than in the init method.

So, we must do here:
Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
Instantiate Date by passing those values to initialization call.
This would look like:

Approximate steps:

    • Parse string, get integer day, month, year.
    • Initializing an object with the resulting information

The code is as follows

Python
12 day, month, year = map (int, string_datesplit ( '-' date1 = Date(day, month, year )

Ideally, the date class itself can have the ability to handle string time, solving reusability problems, such as adding an additional method.

For this purpose, C + + has such feature as overloading and Python lacks that feature-so here's when Classmethod applies. Lets Create another "constructor".

C + + can easily use overloads to solve this problem, but Python does not have a similar feature. So we're going to use Classmethod to help us do that.

Python
12345678 @Classmethod def from_string(cls, date_as_string):   day, Span class= "crayon-v" >month, year = map (int, date_as_string. Split ( '-' ) ) date1 = cls(day, month, year ) return date1 date2 = Date. From_string(' 11-09-2012 ')

Let's look more carefully at the above implementation, and review what's advantages we have here:

We ' ve implemented date string parsing in one place and it's reusable now.
Encapsulation works fine here (if you think so could implement string parsing as a single function elsewhere, this s Olution fits OOP paradigm far better).
CLS is a object that holds class itself, not a instance of the class. It's pretty cool because if we inherit our Date class and all children would have from_string defined also.

Let's take a closer look at the above implementation to see its benefits.

We implement functionality in a method, so it is reusable. The package here is good (if you find that you can also add a function that does not belong to Date anywhere in the code to achieve similar functionality, it is obvious that the above approach is more in line with the OOP specification). The CLS is an object that holds a class (Everything is an object). Even better, the derived classes of the Date class will have a useful way of from_string.

Static method

What's about Staticmethod? It's pretty similar to classmethod and doesn ' t take any obligatory parameters (like a class method or instance method does ).

Let's look at the next use case.

We have a date string, which we want to validate somehow. This was also logically bound to Date class we ' ve used so far, but still doesn ' t require instantiation of it.

Here is where staticmethod can useful. Let's look at the next piece of code:

Staticmethod does not have any required parameters, and classmethod the first parameter is always the CLS, instancemethod the first argument is always self.

Python
1234567 @Staticmethod def is_date_valid(date_as_string):   day, Span class= "crayon-v" >month, year = map (int, date_as_string. Split ( '-' ) ) return Day <= and month <= And year <= 3999 # Usage:is_date = date. Is_date_valid(' 11-09-2012 ')

So, as we can see from usage of Staticmethod, we don ' t has any access to what the class is-it ' s basically just a functio N, called syntactically like a method, but without access to the object and it's internals (fields and another methods), W Hile Classmethod does.

So, as you can see from the use of static methods, we don't access the class itself – it's basically just a function, syntactically, like a method, but without accessing the object and its interior (fields and other methods), instead Classmethod accesses the CLS, Instancemethod will access self.

Reference
      • Meaning of @classmethod and @staticmethod for beginner?

The difference between a Python static method and a class method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.