Python interior decorator (property/staticmethod/classmethod)

Source: Internet
Author: User

Python built-in property, Staticmethod, Classmethod three adorners, sometimes we also use, here is a simple explanation

1. Property

Function: As the name implies, decorate functions as attributes

In general, we call class method members, which are written as follows:

Class PropertyTest ():    def __init__ (self,x,y):        self.x = x        self.y = y    def square (self):        return self.x * Self.ypt = propertytest (3,5) print (Pt.square ())

Here's a look at square as a method of the class, but if it is written in the following form, then it is not certain that the invocation must be a class method:

Class PropertyTest ():    def __init__ (self,x,y):        self.x = x        self.y = y    @property    def square (self):        return self.x * self.ypt = propertytest (3,5) print (Pt.square)

The calling method here is similar to calling a member variable, and if written as print (Pt.square ()) the compiler will error

This is the use of the property, to change a method into a variable to invoke

2, Staticmethod

Function: The method in the class can be called directly without instantiation, as shown below

Class A ():    def __init__ (self):        pass    @staticmethod    def plus (x, y):        print (x*y) c = A () c.plus (2,3) A.plus (4,5)

We can instantiate class A and then call the method plus or directly class. Method call

3, Classmethod

Function: Similar to Staticmethod, the difference is that the calling class is passed in as the first parameter, as follows:

Class A ():    def __init__ (self):        pass    @classmethod    def Plus (cls,x,y):        print (CLS)        print (x*y ) A.plus (4,5) c = A () c.plus (5,6)

Here print (CLS) prints Class A, other usages are the same as Staticmethod

Python interior decorator (property/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.