Document directory
- ◇ Python objects
- ◇ Object Attributes
- ◇ Object type
- ◇ Object ID
- ◇ What are the benefits of "Everything is object?
- ◇ Generalized Encapsulation
- ◇ Narrow Encapsulation
- ◇ Prejudice against access control
- ◇ Python inheritance
- ◇ Inherited syntax
- ◇ Inheritance Dynamics
This series has been interrupted for a long time until a recent reader wrote a letter asking me why I didn't continue writing, so I suddenly remembered this forgotten series. I am really sorry! The previous post introduced python as a dynamic language. Today we will talk about Python's characteristics in Object-Oriented Programming (OOP.
This article focuses on those who are familiar with OOP but are not familiar with python. To give everyone an intuitive understanding, I will use C ++/Java for syntax comparison. (These two languages are well-known and claim to support Oo, which is somewhat comparable)
Note: although some languages are used for comparison, this article does not describe the meaning of these languages at all. Ask fans of these languages not to check their names.
★Abstract action)
Whenever we introduce Oop, we will naturally mention abstraction. Abstract is the first element of OO and the basis of other elements. When it comes to abstraction, we can't help but mention objects ). So, let's first talk about how the Python language reflects objects.
◇ Python objects
If you want to ask what is an object in Python, it is really difficult to define a strict and easy-to-understand definition. To be perfunctory, I had to summarize it in one sentence, that is, in the Python language,All objects. How can I understand this sentence? To put it simply, all the things involved in the Python language are "objects ". For example, a function is an object, a variety of numeric values (such as integer, floating point, and boolean values), an object, a module (similar to a Java package) it is an object, none (similar to null in Java, null pointer in C ++) is also an object ,......
Compare the syntax of C ++ and Java: Only class instances can be regarded as objects. Even basic types (such as int, Char, float, and so on) are not counted as objects. As for functions, they are not even considered.
Since everything is an object, it is necessary to summarize the similarities of Python objects. Otherwise, beginners of python will still be confused.
◇ Object Attributes
First, all Python objects have several attributes. You can use the built-in Dir () function to reflect the attributes of an object. If you are familiar with Java, you should understand what reflection is ". If you have any difficulties in understanding C/C ++, refer to "here ".
In addition, Python provides several built-in functionsRuntimeOperation on the attributes of a specified object. The details are as follows:
Hasattr (OBJ, name) # determine whether the object has the property setattr (OBJ, name, value) named name # Set the property value of the object named name to valuegetattr (OBJ, name) # Get the property value delattr (OBJ, name) of the OBJ object named name # Delete the property named name of the OBJ object
◇ Object type
All Python objects can obtain the object type through the built-in type () function. This is actually the embodiment of Python's rtti mechanism. If you know C ++, you can review the typeid keyword of C ++. If you know Java, you can think about the instanceof keyword.
◇ Object ID
All Python objects can be obtained through the built-in ID () functionUniqueMark. After an object is created, the unique identifier remains unchanged. If you have learned C/C ++, think of this unique identifier as the address of the object in the memory. This may help you understand
The Python object has other commonalities. Considering the literacy nature of this article, it will no longer be a waste of water. If you are interested, you can find some introductory books to study.
◇ What are the benefits of "Everything is object?
Some colleagues may ask, what are the advantages of "Everything is an object? I think: when everything is an object, we can combine many concepts, operations, and conventional methods to reflect the beauty of the syntax.
Let's take a few examples and compare them with Java.
In Java, because the basic type is not inherited from the object class, it brings a lot of trouble. When Java started designing container classes (such as vector, arraylist,...), it took a lot of effort. Because the stuff in the container must be an object, in order to make the container adapt to the basic type, you have to give each basic type a corresponding packaging class derived from the object (the integer class corresponds to the int class, the float class corresponds to the float class ,...); later, the concept of automatic packing/unpacking was added. Python has no such troubles.
Let's talk about it with the "reflection" mentioned just now. Although JAVA supports object reflection, the Java package is not an object, so it cannot reflect the package. In contrast, in Python, after a module (equivalent to a Java package) is imported, you can directly use the Dir () function mentioned above for reflection to find out what the module contains. Only two lines of code are required:
import xxxdir(xxx)
★Encapsulation)
To avoid ambiguity, we must first clarify: what is "encapsulation "? For the sake of convenienceOOPEncapsulation is divided into two types: narrow sense and broad sense. (For more information about encapsulation, see "here ")
◇ Generalized Encapsulation
Oop emphasizes data-centric. Therefore, the broad encapsulation of OOP is to package data and operation data together. For example, the class in C ++/Java can contain both data members and function members, even if it meets the generalized encapsulation. For python, its class keywords are similar to C ++ and Java, and have been encapsulated in a broad sense.
◇ Narrow Encapsulation
The narrow encapsulation of OOP adds information hiding ). For example, the public, protected, and private Keywords of C ++ and Java achieve Information Hiding through access control. Although Python does not modify class members for access control keywords, python uses another mechanism-defined by name. In Python objects, if an attribute is named with a double underline (for example, _ name), it can be similar to private.
◇ Prejudice against access control
I once saw someone in a technical forum questioning Python's access control mechanism, saying that python's private attributes can be bypassed through the reflection mechanism, which is essentially a false one. Here, I want to refute C ++ and Java.
In Java, you can also use the reflection mechanism to access private members of the callback class. As for C ++, thanks to the powerful pointer, as long as you can access an object (this pointer), by calculating the offset of the object member variable in the memory, you can easily read and write it. Although this is quite abnormal, It is theoretically feasible.
★Inheritance)
Next, let's talk about the inheritance topic.
◇ Python inheritance
Python does not distinguish between class inheritance (also called "implementation inheritance" in OO) and interface inheritance like Java, nor is Python like C ++, it separates public inheritance, private inheritance, and protection inheritance. Python has only one inheritance method.
◇ Inherited syntax
The inheritance Syntax of python is more concise than that of C ++/Java. For example, if child of the subclass needs to inherit the parent class, the Code is as follows:
class Child(Parent) :
If it is multi-inheritance, the code is similar:
class Child(Parent1, Parent2, Parent3) :
If you want to know the parent classes (base classes) of a class, you only need to know through child. _ bases.
◇ Inheritance Dynamics
In fact, the previous post introduced an example of dynamically changing the inheritance relationship. However, the last post has been around for a long time (almost one year ago), so many of you may not have read it or have forgotten it. I may try again. As a dynamic language, python canRuntimeModifies the inheritance relationship of a class. This feature is cool, and it is beyond the reach of C ++/Java. See the following example:
Class parent1: def dump (Self): Print ("parent1") Class parent2: def dump (Self): Print ("parent2") class child: def dump (Self ): print ("child") print (child. _ bases _) child. _ bases _ + = (parent1, parent2) # two parent classes of print (child. _ bases _) # The printed parent class information already contains parent1 and parent2
★Polymorphism)
As for the polymorphism of Python, it is similar to the traditional OO language, and it does not seem to be worth mentioning. I will give a simple example of code. In order to save typing, directly reuse the three classes above, and then add another test () function as follows:
def test(obj) : obj.dump()
Then, input different types of objects to the test () function. I don't need to talk about it later?
C = Child () test (c) # print out childp1 = parent1 () test (P1) # print out parent1
★End
Today's topic is to give users who are not familiar with Python a superficial and perceptual understanding of Python's object-oriented features. After talking about Oop, the next post will talk about FP (functional programming.
Return to the directory of this series
Copyright Notice
All original articles in this blog are copyrighted by the author. This statement must be reprinted to keep this article complete, and the author's programming preferences and original addresses in the form of hyperlinks should be noted:
Http://program-think.blogspot.com/2010/08/why-choose-python-3-oop.html