Python:staticmethod vs Classmethod

Source: Internet
Author: User
Tags date1

Being educated under Java background, static method and class method are the same thing.

There is subtle difference:

Say function A () is defined in the parent class, while Sub class extends parent class

    • If function A () has @staticmethod decorator, SUB.A () still refers to definition inside pare NT Class. Whereas,
    • If function A () has @classmethod decorator, SUB.A () would points definition inside Sub Class.

Let's talk on some definitions here:

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It's definition is immutable via inheritance.

@classmethod function also callable without instantiating the class, but it definition follows Sub class, not Pa Rent class, via inheritance. That's because the first argument for @classmethod function must always be CLS (Class).

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

ClassDate(Object):Day=0Month=0 year =0 

Def __ Init__ (self, Day=< Span class= "lit" >0, Month=0 , Year=0): self. Day = day self.= month self.= 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).

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

Classmethod

We have some tasks, which can be nicely-done using classmethod s.

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

So, we must do here:

    1. Parse a string to receive day, month and year as thee integer variables or a 3-item tuple consisting of that variable.
    2. Instantiate by Date passing those values to initialization.

This would look like:

day, month, year = map(int, string_date.split(‘-‘))date1 =Date(day, month, year)

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

@classmethod
DefFrom_string(Cls,Date_as_string):Day, Month, year = Map (int, date_as_string< Span class= "pun". split ( date1 Span class= "pun" >= Cls (day Month, Year) return< Span class= "PLN" > Date1date2 =date. From_string ( ' 11-09-2012 '

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

    1. We ' ve implemented date string parsing in one place and it's reusable now.
    2. Encapsulation works fine here (if you think it could implement string parsing as a single function elsewher Lution fits OOP paradigm far better).
    3. clsis 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.

Staticmethod

What's about staticmethod ? It's pretty similar to and classmethod doesn ' t take any obligatory parameters (like classmethod or instancemethod 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 Date to class we ' ve used so far, but still doesn ' t require instantiation of it.

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

@staticmethod
DefIs_date_valid(Date_as_string):Day,Month,Year=Map(Int, Date_as_string. ( '-' try:assert0<= day <=31assert0<= month <=12assert0<= year <=3999except Assertionerror:returnfalsereturntrue

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 function, call Ed syntactically like a method, but without access to the object and it's internals (fields and another methods), while CL Assmethod does.

Ref:

Http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for

Http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python

Http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner

Http://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods

Python:staticmethod vs Classmethod

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.