[Python] oop concept-Static Method

Source: Internet
Author: User

What is static method?

Python2.73 Doc

Static Method objects
Static Method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. when a static method object is retrieved
From a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation.
Static Method objects are not themselves callable, although the objects they wrap usually are. Static Method objects are created by the built-in staticmethod () constructor.

You do not need to call

Compare

Comparison between general and static methods and definitions and calls
Define a common Class

In [40]: class A(object):   ....:     def met(self,a,b):   ....:         print a,b   ....:

Instance call met Method

In [41]: a = A()In [42]: a.met(3,4)3 4

Call the Met method directly

In [43]: A.met(3,4)---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-43-b2ef395d495e> in <module>()----> 1 A.met(3,4)TypeError: unbound method met() must be called with A instance as first argumen (got int instance instead)

Error, no binding method

Add the instance we created above to the parameter

In [47]: A.met(a,3,4)3 4

Only class instances can be called.

Define a class with a static method:

In [52]: Class B ():....: @ staticmethod ....: def met (A, B): # The first parameter of the static method does not need to be self ....: print a, B ....:

Call after instance

In [55]: b = B()In [56]: b.met(3,4)3 4

Direct call

In [57]: B. Met () # function 3 and 4 can be called without instantiation.

Static methods can be called directly without instance classes, but the first parameter of the method cannot be written in the form of Def (self ,...).

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.