Python 6_encapsulation and inheritance (1)

Source: Internet
Author: User

 

Let's look at a simple example:

# Author liygcheng 2014-04-04 # object-oriented python class Animal (): def _ init _ (self): self. _ name = Animalprint (self. _ name) def accessMethod (self): print (I am a animal, and my name is :) print (self. _ name) print (The Additional message is :) self. _ innerAccess () def _ innerAcess (): print (this can not be seen !) @ Staticmethoddef staticMethod (): print (this is a static method !) @ Property # attribute settings in python def name (self): return self.__name@name.setterdef name (self, value): self. _ name = value@name.deleterdef name (self): del self. _ name

Other problems in this example are not considered for the time being, because during compilation, errors such as "IndentationError: unindent does not match any outer indentationlevel" always occur, after checking on the internet, it turns out that Tab keys and spaces are mixed .. Next, let's take a look at some knowledge points in the Code:

Private functions and static methods are described in detail in the previous class introduction. We will not repeat them here. Here we will focus on this @ property here,

In C ++ or Java, we often encounter setter and getter. Here @ property works similarly. Note that, the three functions in the same attribute must have the same name (name in this example). When using the function, you can set the function as needed, such as whether to read the function only. In fact, before python2.6, there is also a binding method. Let's look at an example:

So what is another binding method? Let's take a look:

We can see that the two effects are the same, but we recommend using the former in python.

2. Inheritance

There may be more inheritance than we did in C ++ and Java for the first time, but the object-oriented thinking remains the same, as in python, we may often find that is-a and has-a in various professional books. The inheritance relationship is a typical is-a (the combination is has-). in inheritance, we should pay attention to the following:

1. When a combination is used to solve the problem, the combination is preferred.

2. the constructor of the successor base class will not be automatically called. You need to explicitly call the constructor of the subclass.

3. Python always searches from bottom to bottom along the inheritance tree

Let's look at a simple example:

Note: When running with subline Text, the "Decodeerror-output not UTF-8" error occurs. Because of Chinese characters, you can directly modify the file in the python plug-in of Subline Text, the procedure is as follows:

1. Find the Python. sublime-build file. The specific location is as follows:

C: UsersliygchengAppDataRoamingSublime Text 2 PackagesPython

2. Add "encoding": "cp936" to the end of the file. Do not forget the last comma in the previous column.


1. As for what cp936 is, Wikipedia explains the following:

Microsoft's CP936 is generally considered to be equivalent to GBK, and even IANA uses "CP936" as the alias of "GBK" [1]. In fact, in comparison, GBK defines 95 more characters than CP936 (15 non-Chinese characters and 80 Chinese characters)

Several questions worth thinking about:

1. when we want to call a method of the parent class in python, if we always use a non-bound class method, that is, reference by class name, and in the parameter list, when this object to be bound is introduced, if the parent class of a subclass changes, all the parent classes must be replaced. The intuition of software engineering tells us that, this is not desirable, because programmers are always lazy. I checked a bit and found that a keyword "super" has been added to python since 2.2 to solve this problem:

The official explanation is as follows:

Super (type [, object-or-type])

Return the superclass of type. If the second argumentis omitted the super object
Returned is unbound. If the second argument is an object, isinstance (obj, type)
Must be true. If the second argument is a type, issubclass (type2, type) must be
True. super () only works for new-style classes.

A typical use for calling a cooperative superclassmethod is:

Class C (B ):
Def meth (self, arg ):
Super (C, self). meth (arg)

New in version 2.2.

In short, we can understand super (type, arg) in this way ). method (..), when executing this statement, first find the parent class of the class type, and then promote the class type or its subclass object arg to the parent class type object of the class type, then, call the method of the parent class of class type. let's look at an example:

 

2. Multiple Inheritance Issues

We know that there is no multi-inheritance in Java and the interface is used directly. In C ++, we introduce the virtual base class. Will this problem occur in python?

Let's take an example:

In this example, we found that using super alone or using non-bound functions alone will be correctly initialized, but when we use super and non-bound methods, note that the parent class is called multiple times.

Next we will analyze the inheritance tree structure of multiple inheritance, and briefly summarize the inheritance tree, such as (saving root objects ):

We learned from the previous results that the class F initialization path is: F-> C-> D-> A. At first glance, we can only determine that this is the initialization from the bottom paper, the specific algorithm used is unknown. The po master checked the information and found that python's multi-inheritance was based on the deep search algorithm before 2.3, however, the C3 algorithm is used to search the inheritance tree,

(Mro, that is, Method resolution order, is mainly used to determine the calling attribute path when multiple inheritance is involved). As to why the C3 algorithm is used, it mainly takes into account the parent class sequence declared during inheritance, in this simple understanding, the C3 algorithm is to first determine a linear sequence, as shown below:

1. If it inherits one base class

Class B ()

At this time, the mro sequence is mro (B) = [B, A]

2. If multiple base classes are inherited

Class B (A1, A2, A3 ,....)

The mro sequence is

Mro (B) =

[B] + merge (mro (A1), mro (A2 ),...., [A1, A2, A3,…])

In this case, the merge operation is the core of the entire C3 algorithm. it traverses the sequence that executes the merge operation. If the first element of a sequence is also the first element in other sequences, otherwise, the element is deleted from all the merge operation sequences and merged to the current mro. The sequence after the merge operation continues the merge operation until the sequence of the merge operation is empty. If the merge operation sequence cannot be empty, it indicates that it is invalid.

For the previous example, let's analyze the inheritance tree: // 0 flag base class object

Mro (A) = [A, 0]

Mro (B) = [B, 0]

Mro (C) = [C] + mro (A) = [C] + [A, 0] = [C, A, 0]

Mro (D) = [D] + mro (A) = [D] + [A, 0] = [D, A, 0]

Mro (E) = [E] + merge (mro (B), mro (C), [B, C])

= [E] + merge ([C, A, 0], [B, 0], [B, C])

= [E, B] + merge ([C, A, 0], [0], [C])

= [E, B, C] + merge ([A, 0], [0])

= [E, B, C, A] + merge ([0])

= [E, B, C, A, 0]

Mro (F) = [F] + merge (mro (C), mro (D), [C, D])

= [F] + merge ([C, A, 0], [D, A, 0], [C, D])

= [F, C] + merge ([A, 0], [D, A, 0], [D])

= [F, C, D] + merge ([A, 0], [A, 0])

= [F, C, D, A] + merge ([0], [0])

= [F, C, D, A, 0]

Now I understand why the Class F initialization sequence is F-> C-> D->.



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.