Static methods and class methods for Python

Source: Internet
Author: User
Tags instance method

Python uses @staticmethod this adorner to make the method a static method

One: Define

@staticmethod: First it is an adorner, the decorated method does not need an implied argument, and an instance of an object and an object can call a static method

The class method is decorated by @classmethod, the first implied parameter of the decorated method is the CLS, and the same object and instance of the object can call the class method

There is also an instance method, which is an instance method, which is bound with an instance, and can only be invoked by an instance, the first implied argument is self

II: Examples

Translated from: Https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python high score answer

The difference between @staticmethod and @classmethod:

classA (object):deffoo (self,x):Print "executing foo (%s,%s)"%(self,x) @classmethoddefClass_foo (cls,x):Print "executing Class_foo (%s,%s)"%(cls,x) @staticmethoddefStatic_foo (x):Print "executing static_foo (%s)"%x a=a ()

1. The following is an instance method call function, where instance A is implicitly passed as the first argument, self

A.foo (1)#  executing foo (<__main__. A object at 0xb7dbef0c>,1)

2. When invoking a class method, the class of the instance is implicitly passed to the function as the first argument, the CLS

A.class_foo (1)#  executing class_foo (<class ' __main__. A ' >,1)

You can also use the class to invoke Class.foo, in fact if you want to define a function as a class function, because most of you want to use the class for access rather than an instance , A.foo (1)

Throw TypeError (instance method cannot be called by Class), but A.class_foo (1) can call normally

A.class_foo (1)#  executing class_foo (<class ' __main__. A ' >,1)

There is also a usage: class methods can be used to create an inheritable dynamic constructor

3. When using Staticmethods, there is no need to suppress the first function, the behavior of the static function in addition to the class method and the instance method can be accessed, and the ordinary method is no different

A.static_foo (1)#  executing static_foo (1)a.static_foo ('hi ' )#  executing static_foo (HI)

Static methods are often used to combine those classes with some of the same logical functions between classes (group functions)

Foo is just a function, but when you use a.foo you are not getting the function, you get the "" "first parameter bound to the part of the instance object a implementation of the function version" ", the Foo function needs to have a parameter,

But a.foo only needs a parameter, a bound to the Foo function, which is what this "bound" means.

Print (A.foo) # <bound method A.foo of <__main__. A object at 0xb7d52f0c>>

Similarly, for a class method, the class is bound to the Foo function's

Print (A.class_foo) # <bound method Type.class_foo of <class ' __main__. A ' >>

Then for a static function, there is no bound object

Print (A.static_foo) # <function Static_foo at 0xb7d479cc>

Three: Class functions can be used for polymorphic

class method is bound to classes, and the quilt class inherits, when the subclass calls into the actual invocation of the sub-type, you can use this subtype to call other class method,
This allows you to override some class method in a subtype to achieve polymorphism. The static method is generally not an override, it is called when it is not bound to the specific parameters, so you can not rely on their own to achieve polymorphism.

>>>classDictsubclass (dict): ...def __repr__(self): ...return "Dictsubclass"... >>> Dict.fromkeys ("ABC"){'a': None,'C': None,'b': None}>>> Dictsubclass.fromkeys ("ABC") Dictsubclass>>>

 

Static methods and class methods for Python

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.