For python beginners, feel different from C. For python beginners

Source: Internet
Author: User

For python beginners, feel different from C. For python beginners

 

I have been reading Python for more than half a month since the beginning. I have read Python core programming and Dive into Python. In other words, I read two books in half a month. I personally know that there are many small programs to be swallowed up. This is also because I have no need to use this book for large-scale development at the moment. It is mainly used for testing small programs. So my strategy is to view the whole page and check it now. The first version of core programming is too old. I am talking about things earlier than 2.2, and I am reading an electronic translation version, which is hard to translate and obscure. After reading this, there will be a bit of cloudification in the fog. If someone on the internet says DIP is good, woodpecker has a free electronic document, please refer to this. It is better than core programming, but it is not suitable for beginners who are reading for the first time. The reason why I think it is better is that some concepts are vague when I read this book. It is hard to understand if a beginner comes up with this book.

In the course of learning, the following are some obvious differences between C and python in the course of reading materials, including the general direction and details. I certainly haven't completed the summary, such as dynamic functions and lambda. In fact, as two completely different languages, the following differences are just the tip of the iceberg. You should at least be interested in the same research as me and be helpful if you are considering learning another language. This article is also a DIP study note. By the way, if you know something about Python, you can recommend some practical Python textbooks. It is impossible to learn well without much hands-on skills.

Objective

My future research direction is embedded. Obviously, C language is my main language. I am not a language enthusiast. I used to think that it is better to be proficient in one language for people who do research rather than use multiple languages. The reason for reading python is mainly because python is more conducive to rapid development of some programs, but also because it is recognized that research and application cannot be separated. I personally think that to compete in computer engineering, you must understand the C language. Because high-performance programming is really required, it is impossible to leave the system architecture of the machine behind and let the Python Virtual Machine (or Java virtual machine, etc.) help you deal with all the underlying layers. More and more CPU cores and more terrible memory performance bottlenecks do not matter to upper-level developers, but they cannot be transparent to high-performance developers. It is more effective to control many applications by yourself. Compilation and C are irreplaceable in these cases. However, it is not enough to know C. Mastering an object-oriented language and a relatively higher level of language will not only benefit future personal development, but also help your technical understanding.

If you want to ask who is more important to me, I think C is more important. The learning curve of C is steep and simple. In fact, there are traps everywhere. It seems that simple and inefficient programs can be done in less than one or two months. When talking about the depth and difficulty of optimization, the skills required are calculated on a yearly basis. However, once you have completed the C language basics, your understanding of computers and other languages will be of great benefit. For example, if you have a C base, you can say that after one day of python learning, you can write some short programs. The subsequent optimization is not a big deal of algorithms. They are all very basic statements for replacement. Of course, this is not to say that Python is not good. In fact, for upper-layer applications, Python is more convenient than C.

Many people think that since C is understood, further understanding of C ++ should be a matter of course, but C ++ is not a superset of C, and I do not like the complexity and complexity of C ++, so I decided to take a look at Python. I like the elegance and quickness of Python.

Language type

Unlike C, Python is a dynamic and strong language. How can this classification be understood? It can be classified according to the following instructions:

Static Language

A language that determines the data type during compilation. Most static type languages ensure this by requiring that their data types be declared before any variable is used. Java and C are static languages.

Dynamic Language

A language used to determine the data type during running, which is opposite to the static type. Python is a dynamic type, because they determine the type of a variable when you assign a value to it for the first time.

Strong Language

A language that always enforces type definition. Java and Python are forced Type Definitions. You have an integer. If it is not explicitly converted, it cannot be treated as a string.

Weak Language

A language that can be ignored. VBScript is of a weak type. In VBScript, you can connect the string '12' and integer 3 to get the string '123', and then you can regard it as an integer 123, all of which do not require any display conversion.

Object Mechanism

To understand this "dynamically determining the variable type", we need to start with the Object mechanism in Python. Objects (hereinafter referred to as an object) is Python's data abstraction. All the data in Python is expressed by the relationship between Objects or Objects. functions are Objects and strings are Objects, everything is an object concept. Each object has three attributes: entity, type, and value. Understanding entities is an important step in understanding objects. Once an object is created, it will not change or be explicitly destroyed. In general, the type (including number, string, tuple, and others) of the operation method supported by the object will not be changed. The change may only be its value. If you want to find a description of a specific point, the object is equivalent to the address of the object in the memory, which actually exists. Both types and values are external representations of objects. Python then provides some interfaces for users to interact with objects. For example, the id () function is used to obtain the integer representation of object objects (actually the address here), and the type () function gets its type.

This object mechanism is not available in c, mainly reflected in the following points:

1 As I mentioned earlier, c is a static type language. We can define int a and char B, but it must be specified in the source code. For example, we can specify a = "lk" in any part of Python. In this way, the type of a is string, which is determined only when a value is assigned, we do not need to explicitly write in the code. In C, we must explicitly specify char * a = "lk", that is, manually specify the type.

2. Since there is no object in C, There is only "Data Representation". For example, if there are two int variables a and B, we want to compare the size, it can be determined by a = B, but if it is two string variables a and B, we have to use strcmp for comparison, because at this time, a and B are essentially pointers to strings. If we use = to compare them directly, the actual value stored in the pointer is the address.

In Java, we can use str1 = str2 to determine whether two string variables point to the same physical memory location. This is called "Object Identity ". To compare two string values in Java, you must use str1.equals (str2 ).

In Python, it is different from the previous two. Because of the introduction of objects, we can use the "is" operator to compare the objects of two objects, it has nothing to do with the type of a specific object. For example, if your object is tuple or string or even class, you can use "is" to compare it, essentially, it is the comparison of "Object Identity", which is similar to = in Java and similar to pointer in C. In Python, = is used for comparison.

3. The introduction of the object mechanism makes Python very flexible to use. For example, we can use the introspection method to view other modules and functions in the memory in the form of objects and obtain their information, and operate on them. In this way, you can define a function without a name, call a function without the declared Parameter order, or even reference a function without a name in advance. These operations are unimaginable in C.

4. Another interesting detail is that the impact of types on object behavior is in various aspects. For example, in the statement a = 1; B = 1, it is caused in Python, it may be a and B pointing to an object with a value of 1 at the same time, or it may point to two objects with a value of 1 respectively. For example, in this statement, c = []; d = [], c and d must point to different, newly created empty list. If it is a "c = d = []" statement? In this case, c and d point to the same list object. These differences are none in c.

Finally, let's talk about why python is slow. The main reason is that function call overhead is large. Because everything is now an object, contruct and destroy are also expensive. Even 1 + 1 is a function call. For example, '12' + '45', create a third string object, then callthe string obj's _ add. We can imagine how fast it can be?

List and array

It is always interesting to analyze arrays in list and C in Python. I believe that some of my friends may, like others, learn from the beginner list as an array. Initially, the difference between list and array is mainly concentrated at two points. First, list can contain many different data types, such

["This", 1, "is", "an", "array"]

This List, if put in C, is actually a string array, equivalent to two-dimensional.

Second, there are many methods to list, which are itself an object, which is different from the pure array of C. List operations are diverse because there are methods and overloaded operators. There are also some problems, such as the following example:

To generate a multi-dimensional list, use the following statement.

A = [[None] * 2] * 3

As A result, the value of A is

[[None, None], [None, None], [None, None]

No problem at first glance. A typical list in two-dimensional array form. Now we want to modify the value of the first None, using the statement

A [0] [0] = 5

Now let's take A look at the value of:

[[5, None], [5, None], [5, None]

No problems found? This is because when * is used for copying, it only creates a reference to this object, rather than creating it. * 3 create a list containing three references, all of which point to the list with the same length of 2. Changes to one of the rows will be displayed in all rows, which is certainly not what you want. Of course, there are solutions. We will create them in this way.

A = [None] * 3
For I in range (3 ):
A [I] = [None] * 2

In this way, a list containing three different lengths of 2 is created.

Therefore, we have always stressed that the more complex things are, the more flexible they are, the more error-prone they are.

Code optimization

C is a very simple language. When we consider optimization, we usually think about it very easily. For example, the fewer system-level calls, the better (the buffer mechanism ), eliminate cycle inefficiency and unnecessary system references. In fact, they are mainly based on system and hardware details. Python is completely different. Of course, the optimization methods mentioned above are still practical for Python. However, due to the wide variety of Python syntax forms, there are various libraries and modules, therefore, for the language itself, there are many optimization points worth attention. Let's give a few examples.

For example, we have a list L1, and we want to build a new list L2. L2 includes the first 4 elements of L1. According to the most direct idea, the code should be

L2 = []
For I in range [3]:
L2.append (L1 [I])

The more optimized and elegant version is

L2 = L1 [: 3]

For example, if s1 .. s7 is a large string (10 K +), So join ([s1, s2, s3, s4, s5, s6, s7]) it will be much faster than s1 + s2 + s3 + s4 + s5 + s6 + s7, because the latter will calculate many subexpressions and join () all the copies are completed in one process. Also, for string operations, use the replace () method for string objects. The regular expression is used only when there is no fixed string mode.

Therefore, optimization is the criterion. If C is short and refined, Python is profound and profound.

Include and import

In C language, include is very simple, because the form is single and the meaning is clear. When you need to use external functions and other resources, use include. Python has a similar mechanism, namely import. At first glance, these two guys are very similar. Don't we use this to specify them when we use external resources (the most common is a function or module (Python? Actually, the essential difference between the two processing mechanisms is that the include in C is used to tell the Preprocessor the content of the file specified by this include, you have shown it to me as a local source file. But the import is not simply to insert the following content * directly * into the local, which is more flexible. In fact, almost all similar mechanisms, Python is more flexible than C. This is not to say that C is not good, and C is concise. I actually prefer C.

Let's briefly talk about this flexibility. There are three types of import in python: import X, from X import * (or a, B, c ......), X = _ import _ ('x '). The second method is most commonly used, because it is more convenient. Unlike the first method, X. module is always used to call modules. From X import * only imports public modules (usually modules not named after _). You can also specify a, B, and c to import them.

When will this form be used? It should be said that in most module documents, you will be clearly indicated which form should be used. If you need to use many objects, the from X import * format may be more suitable. However, currently, most third-party Python libraries do not recommend the from modulename import * format. This will confuse the Creator's namespace. Many people do not even use this method for modules specifically designed for this mode, including Tkinter, threading, and matplot. If you only need an object class a, use from X import a to use import X. a is better, because in the future you will call function a to directly use function. function () can be used without adding X.

What if you don't even know the module you want to import? Note that the advantages of Python are shown in this case. We can use _ import _ (module) to call the module, where this module is a string. In this way, you can decide at runtime What module you want to call. For example:

Def classFromModule (module, Name ):
Mod = _ import _ (module)
Return getattr (mod, Name)

The classFromModule function is defined here. You can call it anytime in the code,

O = classFromModule (ModuleOfTheClass, NameOfTheAttribute )()

You only need to pass in the string form. The module ModuleOfTheClass you want to import and the attribute name NameOfTheAttribute (of course, it can be data or method) can be called, this name string does not need to be specified in advance, but is determined based on the current running situation.

By the way, the import sequence in Python is also set by default. This is a bit similar to the include in C, because we usually include system files first, include your own header file (and the difference between <> and ). In Python, the import module should generally follow the order below:

1. Standard library modules-such as sys, OS, and getopt

2. Third-party modules

3. Local implementation module.

Global Variables

Here we will talk about global variables. It doesn't mean that the global variables of Python and c are different. Their concepts are the same. There are some differences in the usage mechanism. For example:

-Module. py-
Globalvar = 1

Def func ():
Print globalvar
# This makes someglobal readonly,
# Any attempt to write to someglobal
# Wocould create a new local variable.

Def func2 ():
Global globalvar
Globalvar = 2
# This allows you to manipulate the global
# Variable

In the func function, globalvar is read-only. If you use the value assignment statement globalvar = xxx, Python creates a new local object and assigns it a new value. The original object value remains unchanged. In the func2 function, because we stated in advance that globalvar is global, the change takes effect directly on the global variable.

 

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.