Python Staticmethod&classmethod

Source: Internet
Author: User
Tags date1

Both of these methods in Python are done through decorators.

Static Methods

You do not need to pass an instance of a class object or class

You can pass an instance of the class. Method name A (). foo () or class name. Method A.foo () name to access

When the subclass inherits the parent class, and when the subclass is instantiated, the instance is actually the parent class, not the child class.

The invocation of a static method is the same as a call to a normal method , except that the preceding class name is added.

Static methods are not too large to use, mainly considering the encapsulation of code, maintainability

Class method:

The default transitive class object itself is CLS, which can of course take advantage of the methods in the class

You can pass an instance of the class. Method name A (). foo () or class name. Method A.foo () name to access

Methods work correctly when subclasses inherit from parent class

Class Date (object):

Day = 0

Month = 0

Year = 0

def __init__ (self, day=0, month=0, year=0): #存储初始的信息

Self.day = Day

Self.month = Month

Self.year = Year

Print Self.day, Self.month, self.year

@classmethod

def from_string (cls,date_string):

Day, month, year = map (int, date_string.split ('-'))

Date1 = CLS (Day, month, year) #cls是个类对象, not an instance

Return Date1 #返回Date实例

def foo (self):

print ' I am foo ' #普通的方法

@staticmethod

def is_date_valid (date_string): #验证方法封装在类中

Day, month, year = map (int, date_string.split ('-'))

Return day <= and month <= <= 3999

---------------------------------------------------------------------------------------------

A=date (a)

1 2 3

>>> a=date.from_string (' 09-08-2015 ')

9 8 2015

>>> A.foo ()

I am Foo

>>> date.is_date_valid (' 10-10-2015 ')

True

>>> type (date.is_date_valid)

<type ' function ' >

Python Staticmethod&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.