Python little Note (5)

Source: Internet
Author: User

Static Methods and Class methods

First look at the following code

#!/usr/bin/env python#coding:utf-8class Foo(object):        #Python 3: class Foo:    one = 0    def __init__(self):        Foo.one = Foo.one + 1def get_class_attr(cls):    return cls.oneif __name__ == "__main__":    f1 = Foo()    print "f1:",Foo.one        #Python 3: print("f1:"+str(Foo.one)),下同,从略    f2 = Foo()    print "f2:",Foo.one    print get_class_attr(Foo)

In the above code, there is a function get_class_attr() , the parameters of this function I use cls , from the code of the body of the function to see that the object it refers to should have attributes one , which means that it is not a random object can be. Just so coincidentally, I Foo have this attribute in the class that I defined earlier one . So, when I call this function, I pass the class object directly to it get_class_attr(Foo) .

The results of the operation are as follows:

f1: 1f2: 22

In this program, the function is get_class_attr() written out of the class, but in fact, the function can only invoke the class object that was written earlier, because not all objects have that particular property. Therefore, this kind of writing, makes the class and the function coupling is too strong, does not facilitate later maintenance. This kind of writing should be avoided. The way to avoid this is to combine functions with classes. So there is the following wording.

#!/usr/bin/env python#coding:utf-8class Foo(object):    #Python 3: class Foo:    one = 0    def __init__(self):        Foo.one = Foo.one + 1    @classmethod    def get_class_attr(cls):        return cls.oneif __name__ == "__main__":    f1 = Foo()    print "f1:",Foo.one    f2 = Foo()    print "f2:",Foo.one    print f1.get_class_attr()    print "f1.one",f1.one    print Foo.get_class_attr()    print "*"* 10    f1.one = 8    Foo.one = 9    print f1.one    print f1.get_class_attr()    print Foo.get_class_attr()

In this program, there has been--the decorator--has been @classmethod encountered in the part of the function. It is important to note that in the parameters of the @classmethod decorated method, the first parameter is not self , which is different from the method in the class we saw previously. Here I use the parameters cls , you can use anything else, just used cls .

Then look at the use of the class process. First, the execution results of the above program are posted:

f1: 1f2: 22f1.one 22**********899

Two instances are created, after which Foo.one the value of the Class property is 2, and the method is called by instance and class respectively get_class_attr() (no write arguments are displayed cls ), and the result is the same.

When you modify class properties and instance properties, the method is called again through the instance and the class, and the get_class_attr() result of the class property is still obtained. This shows that the adorner @classmethod decorates the method whose arguments cls refer to the object that is the class object Foo .

At this point, you can define the next.

The so-called class method, which is the method defined in the class, is decorated by the adorner @classmethod , and its first argument refers to the cls class object, and the class itself is passed into this method as a reference object.

After understanding the class method, use the same routines to understand another method-static method. Look at the code first-a code that needs to be optimized.

#!/usr/bin/env python#coding:utf-8T = 1def check_t():    T = 3    return T class Foo(object):        #Python 3: class Foo:    def __init__(self,name):        self.name = name    def get_name(self):        if check_t():            return self.name        else:            return "no person"if __name__ == "__main__":    f = Foo("canglaoshi")    name = f.get_name()    print name        #Python 3: print(name)

First, the above procedure is observed, and it is found that the Foo functions defined outside the class are used check_t() . The relationship between this class and function is also due to the close relationship, which leads to difficulty in maintenance of the program, so under the same reasons as before, there is a relatively easy to maintain the following procedures.

#!/usr/bin/env python#coding:utf-8T = 1class Foo(object):        #Python 3: class Foo:    def __init__(self,name):        self.name = name    @staticmethod    def check_t():        T = 1        return T    def get_name(self):        if self.check_t():                   return self.name        else:            return "no person"if __name__ == "__main__":    f = Foo("canglaoshi")    name = f.get_name()    print name        #Python 3: print(name)

It is optimized to move the functions that were originally placed outside the class into the class, that is, the function check_t() is now Foo within the namespace of the class. However, it is not simple to move, but also to precede this function with an @staticmethod adorner, and note that although the function is inside the class, unlike other methods, it is not used self as the first parameter. When it is used, it can be called through an instance, self.check_t() or it can be called through a class, for example Foo.check_t() .

As can be seen from the above program, although check_t() it is within the namespace of the class, it is an independent method, it has nothing to do with the class, just to avoid the previous maintenance difficulties, written in the scope of the class of ordinary functions. However, its existence also makes sense, the above example is a typical description. Of course, in the scope of the class, the front must be preceded by an adorner @staticmethod . We also give this method a name, called a static method.

Method, is an important part of the class. This section is devoted to several special methods in the method that provide a more convenient tool for our methods of using classes. However, one of the important characteristics of the class-inheritance, has not yet appeared.

Python little Note (5)

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.