Python classes: Class methods and Static methods

Source: Internet
Author: User
Tags instance method

http://blog.csdn.net/pipisorry/article/details/49516185

In the design of face object, class method and static method are the two terms commonly used.
Logically: A class method can only be called by a class name, and a static method may be called by a class name or object name.
In C + +, a static method is logically equivalent to a class method, and there is only one concept that is not confused.
In Python, methods are divided into three types of instance methods, class methods, and static methods.

@classmethod and @staticmethod

Their use of the scene is not the same. In Python, the main difference between the two methods is that the parameters

    • The common method inside the class is to pass the scope self of the instance into the method as the first parameter, which means that it is called by the instance;
    • @classmethodclsas the first parameter, represents the scope in which the class itself is passed in. Whether invoked through a class or by an instance of a class, the first parameter passed in by default will be the class itself
    • @staticmethodNo need to pass in default parameters, similar to a normal function
The instance method implies that the argument is the class instance self;
A class method implicitly has a parameter that is the class itself CLS;
Static methods have no implicit arguments, and they can also be called directly to a class instance.

The logical class method should be called only by the class, the instance method instance, and both of the static methods can be called.

In fact, Python implements some flexibility so that both class and static methods can be called by both instances and classes.

Phi Blog



Example Example 1

#!/usr/bin/env python#-*-Coding:utf-8-*-"""__title__ = ' Python instance method, class method and static method difference and use '__author__ = ' Skin '__email__ = ' [email protected] '# code is far away from bugs with the god animal protectingI love animals. They taste delicious."""ImportTracebackclassT:    defInstancemethod( Self):        Print("Instance method!")Print( Self)@Classmethod    defClassmethod(CLS):        # def Classmethod (self): #当然这样也不会出错        Print("Class Method")Print(CLS)@Staticmethod    defStaticmethod():        Print("static method") T= T () T.instancemethod () T.classmethod () T.staticmethod () T.classmethod () T.staticmethod () T.instancemethod (t)# the wrong situationTry:    T.classmethod (T) T.instancemethod ()except:    Print(Traceback.format_exc ())

Example 2

Suppose we need to create a class called date that stores three data per year/month/day
Class Date (object):
def __init__ (self, year=0, month=0, day=0):
Self.year = Year
Self.month = Month
Self.day = Day

@property
def time (self):
Return "{year}-{month}-{day}". Format (
Year=self.year,
Month=self.month,
Day=self.day
)
The code above creates the date class, which sets the Day/month/year property at initialization time, and a getter is set through the attribute, which can be used to get the stored time after the instantiation:
Date = Date (' 2016 ', ' 11 ', ' 09 ')
Date.time # 2016-11-09
But what if we want to change the way attributes are passed in? After all, it is annoying to pass the three properties of the year/month/day when initializing. Can you find a way to create a date instance by passing in a string such as 2016-11-09, without altering the existing interfaces and methods?
You might think of such a method:
date_string = ' 2016-11-09 '
Year, month, day = map (str, date_string.split ('-'))
Date = Date (year, month, day)
But not good enough:
Extra write a method outside of the class, each time you have to format to get the parameters
This method is only associated with the date class.
Problem with too many incoming parameters not resolved
At this point, you can use @classmethod to create a new format string inside the class and return an instance of the class method:
# Add a Classmethod to Date
@classmethod
Def from_string (CLS, string):
Year, month, day = map (str, string.split ('-'))
# within Classmethod, you can call methods to classes through the CLS, even create instances
Date = CLS (year, month, day)
Return date
This allows us to invoke the From_string method through the date class to create an instance without invading or modifying the old instantiation:
Date = date.from_string (' 2016-11-09 ')
# old instantiation mode can still be used
Date_old = Date (' 2016 ', ' 11 ', ' 09 ')
Benefits:
Within @classmethod, it is possible to obtain the same convenience as the external calling class through the CLS parameter.
The method can be further encapsulated in it to improve reusability
More compliant with object-oriented programming
and @staticmethod, because it is similar to the normal function, so can be associated with this class helper method as @staticmethod, put in the class, and then directly through the class to invoke the method.
# Add a Staticmethod to Date
@staticmethod
def is_month_validate (month):
return int (month) <= and Int (month) >= 1
After you put date-related auxiliary class functions in the date class as @staticmethod methods, you can call these methods through the class:
month = ' 08 '
If not date.is_month_validate (month):
Print (' {} is a validate month number '. Format (month))

from:http://blog.csdn.net/pipisorry/article/details/49516185

Ref: [Static Methods and Class Methods?] *

Python class: Class

[Python @classmethod and @staticmethod for beginner]

[difference between Staticmethod and Classmethod in Python]


Python classes: Class methods and Static methods

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.