24. Class methods in python, 24. python Methods

Source: Internet
Author: User

24. Class methods in python, 24. python Methods

Methods in the class are actually functions in the class, which can be divided into instance methods, class methods, and static methods. Methods are similar to fields and belong to class attributes. Therefore, they also have special effects for modifications during running. However, this is generally not recommended.

In the basic syntax of the class, I introduced the constructor method: __init _, _ new __; deconstructor method: __del __;

Note: although it starts with two underscores (_), it ends with two underscores (_). Here it indicates that it is a 'magic method'. For the magic methods in the class, I will explain this article.

However, if we start with only two underscores, it still means privatization. Let's look at the code example:

Class Test (object): def _ scolia _ (self): # A magic-like method is not private return 'scolia 'def _ good (self ): # private method return 'good' a = Test () print. _ scolia _ () # The Magic method can directly access print. _ good () # private methods cannot be accessed directly

 

Similarly, like the field privatization, we may also force access through the same special means:

Print a. _ Test _ good () # force access

 

Of course, private methods can also be accessed within the class, just like private fields.

Therefore, the private properties are obfuscated with access entries. Similarly, it is not recommended to forcibly access private properties.

The 'Magic method' here may not seem 'magine'. The details will be explained later.

Instance method:

In the _ init _ constructor, it is mentioned as an instance method. The features of the instance method are as follows:

1. The first parameter of the method must be self. Of course, this is a convention. You can replace self with abc. But for other programmers to understand it, use self in a unified manner. Here, self indicates the instance itself. That is to say, if I use a = Test () during instantiation, self indicates the instance, we can see in many constructors similar to self. scolia = 'good'. Actually, this method is used outside the Class. scolia = 'good' has the same effect. It is used to add attributes, but the _ init _ method is a function automatically called during instantiation. Therefore, it is suitable for initial attribute creation.

2. self is automatically transferred when the instance method is called, so we do not need to process it again.

3. The instance method can be called only when an instance is available. Of course, there are also special call methods.

Sample Code:

Class Test (object): def _ init _ (self, a, B): # The constructor initializes the property self when the instance is created. a = int (a) self. B = int (B) def abc (self, c): # instance method print self. a + self. B + int (c) # Because self is automatically passed, we can call the instance property a = Test (123,321) in the instance method) # We only need to pass parameters a and B. abc (666) # similarly, as long as the parameter is passed for c

 

Here, we will introduce a binding concept, which is mainly related to method calls.

First, we know that the method is a class attribute, not an instance attribute. We also discussed this issue in the attributes of the class and instance in the previous blog.

Second, a method can be called only when its class has an instance. When a class exists, the method is considered to be bound to this instance. When no instance is available, the method is not bound.

Finally, the first parameter of any method definition is the variable self, which indicates the instance object that calls this method.

Obviously, the binding here is for the instance method. If there is no instance, self cannot be passed, which will lead to insufficient parameters and of course cannot be called.

  HoweverYou can pass self to call unbound methods. Calling unbound methods is usually after we inherit a parent class, we overwrite a method in the parent class, but in order to achieve code reuse, we also want to call the method of the parent class in the subclass. Simply copying the code in the parent class is obviously not a good choice. In addition to wasting system resources, there may also be errors during replication, and after modifying the code of the parent class, it is too inefficient to modify the code in the corresponding subclass. This is the scenario where the unbound method is called.

Sample Code:

Class abc (object): def _ init _ (self, a): self. a =-int (a) class Test (abc): def _ init _ (self, a, B): abc. _ init _ (self, a) # Call the constructor of the parent class and manually pass self. B = B def fangfa (self): print self. a + self. B # attribute a is created by the constructor of the parent class, and B is created by the sub-class constructor a = Test (123,321) # We only create sub-class instances, instance. fangfa ()

 

If we didn't create an example of a parent class, we could not call the instance method of the parent class. However, we manually passed the self parameter required by the instance method to implement the call.

The order here is that we created the Test instance and Its self is automatically passed. Therefore, the Test constructor _ init _ (self, a, B) in self indicates instance a, and we call the abc of the parent class. _ init _ (self, a) Here, self is the sub-class instance a, parameter a is the passed 123, and self in the parent class. a =-int (a); finally, we can call self in the subclass method. a.

 

 

Class method:

The class method is actually similar to the instance method, but its first parameter is cls rather than self. However, it is incorrect to replace self with cls to create a class method, because the first parameter of the instance method is arbitrary, but the self is used in a unified manner. The interpreter of python does not say that the first parameter is cls and it knows that this is a class method. It still treats it as an instance method, so we need to use the built-in function: classmethod () to create class methods.

Sample Code:

Class Test (object): def abc (cls): print cls. _ name _ # print the class name abc = classmethod (abc) # create the class method a = Test () Test by passing parameters through common functions. abc () # class can call. abc () # The instance can also be called

 

Of course, some people think of the decorator when they see this Code. In fact, we can also use the decorator method to create a class method:

Class Test (object): @ classmethod def abc (cls): print cls. _ name _ # print class name

 

The results are the same. The specific choice depends on your preferences.

Note that because the classmethod () function is used, the first cls parameter of the classmethod () function is fixed and represents the current class. There is no call form for non-binding methods in the instance method.

 

 

Static Method:

A static method is actually a common function in the class. It does not have the default parameter passed. When creating a static method, you need to use the built-in function: staticmethod ().

Sample Code:

Class Test (object): def abc (): print 'abc' abc = staticmethod (abc) @ staticmethod def xyz (a, B): print a + bTest. abc () # class calls Test. xyz (1, 2) # class call a = Test (). abc () # instance call. xyz (3, 4) # instance call

 

Note: although the static method does not have a default parameter, it does not mean that there is no parameter.

 

Summary:

  1. The instance method requires at least one default parameter self.

2. The class method requires at least one default parameter cls.

3. default parameters are not required for static methods.

In addition, methods are also attributes, so we can use self. abc (), cls. abc () method to call other methods in the class, of course, pay attention to the parameter passing problem.

 

Impersonate fields using methods:

  Sometimes, after a series of processing operations, one of our methods returns a data, for example:

Class Test: def _ init _ (self, a, B): self. a = a self. B = B def fangfa (self): c = self. a + self. B return c # return the processed result data a = Test (1, 2) B =. fangfa () # Call the method to obtain the returned value print B

 

However, the lazy programmers thought: All I want is data similar to a field, but I want to call a method. Sometimes it is easy to make a mistake. Can I retrieve data in the form of a field? This is more intuitive.

Yes. You only need to use the property () function. Similarly, there are two ways to create a decoration device:

Class Test: def _ init _ (self, a, B): self. a = a self. B = B @ property def fangfa (self): c = self. a + self. B return ca = Test (1, 2) B =. fangfa # print B without parentheses

 

In this way, the method is disguised as a field. In fact, the lazy programmers do not want to write more parentheses. Of course, there are some other advantages.

 In addition, the function must use the return value. Otherwise, the default value is None.

In the classic category, we can only do this.

However, if you use a new class, you will have more features:

Class Test (object): def _ init _ (self, a, B): self. a = a self. B = B @ property def fangfa (self): c = self. a + self. B return c @ fangfa. setter def fangfa (self, value): self. a = value @ fangfa. deleter def fangfa (self): print 'Property deleted 'a = Test (1, 2) B =. fangfa # obtain the method's return value print ba. fangfa = 100 # Run fangfa. setter modifier, and make the value = 100 print. adel. fangfa # execute fangfa. er modification method

  Note the name of the last two decorator..

In addition, the method must be decorated by the property () function before the subsequent two decorators can be used.

If you use a non-decorator:

Class Test (object): def _ init _ (self, a, B): self. a = a self. B = B def fangfa_get (self): c = self. a + self. B return c def fangfa_set (self, value): self. a = value def fangfa_del (self): print 'attribute deleted 'fangfa = property (fangfa_get, fangfa_set, fangfa_del)

 

Property (fget = None, fset = None, fdel = None, doc = None)

The last doc is the instruction document. If you need to add it, you can access it through Test. fangfa. _ doc.

There are so many methods first, and you need to modify them later.

 

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.