Python program Structure (2)--method/method, static methods, class methods, and Property methods

Source: Internet
Author: User
Tags call back instance method

Tag: Call back object-oriented Python one digital ASSM mode not

Static methods, class methods, and Property methods

There are three common method decorators in Python (refer to the Adorner section), so that ordinary class instance methods can be transformed into methods with special functions, such as static methods, class methods, and property methods.

Static Methods /Static Method

You can make this method static by adding @staticmethod to it before the DEF definition, and static methods cannot invoke instance properties . A static method can be called through an instance or class . It is often used in methods that do not need to generate instances or share instance properties, such as some purely mathematical formula calculations.

1 class Foo (): 2     @staticmethod 3     def Foo (A, b): 4         Print ('This is a staticmethod, cal result:%d' % (A +b)) 5 6 Foo.foo (1, 2)7 foo (). Foo (3, 4)

A simple Foo class is defined in the code, and a Foo static method is defined by adding a static method adorner, which shows the results of the two arguments passed in, which can be defined as a static method because the properties of the instance or instance are not needed in the entire method.

 is a staticmethod, Cal Result:3 is a staticmethod, Cal Result:7

From the results of the output, you can call a static method whether you are using a class or a class instance.

class Method /Class Method

The definition of DEF is preceded by a @classmethod to decorate it so that the method becomes a class method, the class method cannot invoke the instance property , but the class property can be called, and the class method can pass the instance or class Make the call. At the same time, class methods can be used to do some processing of classes before the class is instantiated.

1 classFoo:2num = 13     4 @classmethod5     definstance (CLS):6Cls.num = 77CLS =CLS ()8         returnCLS9     Ten     def __init__(self): OneSelf.foo =Foo.num A  -     defTest (self): -         Print('This is a test') the  -Cls_1 =Foo () - Print("Foo is:%d, num is:%d"%(Cls_1.foo, cls_1.num)) -          + #Change num from 1 to 7 before __init__ -Cls_2 =foo.instance () + Print("Foo is:%d, num is:%d"%(Cls_2.foo, cls_2.num)) ACls_2.test ()

In the above code, a class method is defined, which modifies the Num property of the Foo class at the time of invocation, and then generates a class instance (line 7th, which actually completes the initialization of a class) and returns. First do not call the class method, directly generate a class instance cls_1, then look at the property values in Cls_1, and then use the class method, call the instance method directly through Foo to generate a class instance cls_2, and the same view of the properties in the class instance, and finally call the test method to test whether this class instance can invoke an instance method like a normally generated class instance.

 is is: 1are: 7 is a test

The final output shows that the properties in the directly generated class instance cls_1 are not changed, while the properties in the class instance cls_2 generated by the class instance method change, and the cls_2 can also invoke the normal instance method. This means that the class method can be directly called through the class without having to be instantiated first, and the first parameter that the class method passes into is the current class .
Note: This kind of method can be used in Singleton mode (refer to Singleton mode ) to ensure that a class has only one instance object present regardless of how many times it is instantiated.

Property Method /Property Method

The definition of DEF is preceded by a @property decoration, which makes the method a property method, and the property method can be called directly outside the call property, if you need to implement the modification of the property method value, you also need to define the @ Methodname.setter decoration of the same name method, in this method to implement the property method return value modification.

1 classFoo (object):2     3     def __init__(self):4Self._foo =None5         6 @property7     deffoo (self):8         returnSelf._foo9     Ten @foo. Setter One     deffoo (self, value): A         ifisinstance (value, int): -Self._foo = (value + 0.5) -              the if __name__=="__main__": -f =Foo () -     Print("Foo is%s"%F.foo) -F.foo = 1 +     Print("Foo is%s"% F.foo)

The above code defines an attribute method for Foo and a setter for the property method, so that the Foo method is used as a property, can be called directly from the instance (17th/19), and @foo. Setter decorators are also assigned the Foo attribute method Ability to pass a parameter (line 18th) directly to Foo through a similar attribute assignment, and you can also perform certain operations on the incoming parameter (such as line 12th/13).

is is 1.5 

As can be seen in the results of the final output, Foo is a method, but it is used in a way that is quite similar to a property, the functionality provided by the property method is very effective in object-oriented programming, and can often be done by defining a property method to implement the operation of a series of objects. To make an instance closer to the behavior of the real object (the above example may not be very appropriate, but it can be understood as a recognizer, as long as the number passed in, it modifies its own _foo property to the value of +0.5, but outside the need not care about this implementation, only Foo as a property assignment).

Python program Structure (2)--method/method, static methods, class methods, and Property methods

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.