Python has been around for more than half a month now, looking at Python core programming and dive into Python two books. Say half a month to see two, is the individual know how swallowed, this is also because I do not need to take this to do large-scale development, the main is usually the small program test with a use. So my strategy is, the overall browsing, with the time to investigate. The first version of the core programming is too old, old in the 2.2 before the thing, I read the translation of electronic version, translation is not good, very obscure. After reading this also a bit foggy, see online people say dip good, woodpecker also has free electronic documents, look for this. How to say, speak more than the core programming good, but not suitable for the first time to see the beginner. The reason I feel good about it is because I look at core programming, some of the concepts are still vague, and reading this book is quite clear. If the beginner comes up to read this, make sure not to understand.
The following is in the process of learning, in the process of flipping through the data, summed up some C and python more obvious differences, there are large directions, there are details. Certainly not summed up, such as dynamic functions, lambda These, I do not bother to write. In fact, as two completely different languages, the following differences are just the tip of the iceberg. Right, at least it should be helpful to a friend who has the same research interests and is considering whether to learn another language. This article is also a dip in the study notes it. Incidentally, if you have a friend to understand, you can help recommend the actual combat of Python teaching materials, language this thing, not much practiced hand, light gestures, it is impossible to learn.
Purpose of study
My future research direction is embedded, obviously, C language is my main language. I'm not a language enthusiast, and I used to think that it's better to be proficient in a language than a person who does research rather than application. The reason to look at Python is that Python is more conducive to the rapid development of some programs, but also because it is now recognized that research and application can not be separated. Personally, to want to be in the computer engineering competition in the foothold, must understand C language. Because you really want to do high-performance programming, it's impossible to put the machine's architecture behind your head and let Python VMs (or Java virtual machines, etc.) take care of all the bottom layers. More and more CPU cores, more and more scary memory performance bottlenecks, for the upper-level developers, it doesn't matter, but for high-performance program developers, these are not transparent. Many applications, or self-control more effective. In these cases, compilations and C are irreplaceable. However, the light know that C is not enough, master an object-oriented language, relatively high-level language, not only for future personal development benefits, but also to their own technical understanding to help.
If you want to ask who is more important to me, I think C is more important. C's learning curve is steeper, seemingly simple, in fact, everywhere is a trap, it seems relatively simple and inefficient program, it is not learning 1, 2 months can be done. When it comes to the depth and difficulty of optimization, the required foundation is calculated on an annual basis. But once you have the basics of C, your understanding of the computer is good for other languages. For example, if you have a C base, you can say, learn python for 1 days, you can write a few short programs. The back of the optimization is not a big deal of the algorithm, are very basic statements in exchange for. Of course, this is not to say that Python is bad, in fact, the upper application, Python than C convenient is not a level.
Many people think, since understand C, then the further mastery of C + + should be the case, but C + + is not a superset of C, and I do not like C + + cumbersome and huge, so decided to look at Python. I love the elegance and quickness of Python.
Language type
Unlike C, Python is a dynamic type language and a strongly typed language. How do you understand this classification? Presumably it can be categorized according to the following instructions:
Static type language
A language that determines the data type during compilation. Most static type languages guarantee this by requiring that their data types be declared before any variables are used. Java and C are statically typed languages.
Dynamic type language
A language that determines the data type during runtime, as opposed to a static type. Python is a dynamic type because they determine the type of a variable when you first assign it a value.
Strongly typed languages
A language that always enforces type definitions. Java and Python are mandatory type definitions. You have an integer that cannot be treated as a string if it is not explicitly converted.
Weakly typed languages
A type of language that can be ignored, as opposed to a strong type. VBScript is a weak type. In VBScript, you can concatenate the string ' 12′ and integer 3 to get the string ' 123′, and then you can think of it as an integer 123, all of which do not require any display conversions.
Object mechanism
Specifically how to understand this "dynamic determination of variable type", it is necessary to start with the Python object mechanism. Objects (hereinafter referred to as the object) is the abstraction of Python for data, all data in Python is represented by the relationship between objects or objects, functions are objects, strings are objects, and everything is the concept of objects. Each object has three properties: entity, type, and value. Understanding an entity is an important step in understanding an object, and once it is created, it will never change or be explicitly destroyed, and in general sense the type (type, including number,string,tuple and other) that determines how the object supports it will not change. It is only possible to change its value. If you want to find a specific point of the description, the entity is equivalent to the object in memory address, is the essence of existence. The type and value are just the external rendering of the entity. Python then provides interfaces that allow the user and the object to interact, such as the ID () function to get the shape representation of an object entity (which is actually the address here), and the type () function to get its types.
This object mechanism, which is not available in C, is mainly embodied in the following points:
1 just now, C is a static type language, we can define int a, char B and so on, but must be specified in the source code beforehand. For example, we can directly specify a = "lk" in Python, so that the type of a is string, which is determined at the time of its assignment, and we don't have to write it explicitly in the code. In C, we have to explicitly specify char *a = "LK", which is the type of manual pre-defined a
2 because in C, there is no object this concept, only "data representation", for example, if there are two int variables A and b, we want to compare size, we can use a = = B to judge, but if it is two string variables A and B, we have to use strcmp to compare, because at this time, A and B are essentially pointers to strings, and if you compare them directly or by = =, the comparison is actually the value stored in the pointer-the address.
In Java, we can determine whether two string variables point to the same physical memory location by using STR1 = = STR2, which is called "Object identity." To compare two string values in Java, you would use Str1.equals (STR2).
Then in Python, unlike the first two, due to the introduction of the object, we can use the "is" operator to compare the entities of two objects, and the type of the specific object is not related, such as your object is a tuple or string, or even class, can be used " Is "to compare, essentially is the" object identity "comparison, and Java is similar to = =, and C in the pointer is similar. Python also has a = = comparison, this is the value comparison.
3 Because of the introduction of the object mechanism, it is very flexible to use Python, for example, we can use the introspection method to see the memory in the form of objects in the existence of other modules and functions, get their information, and manipulate them. In this way, you can define a function without a name, call the function in the order of the arguments of the function declaration, or even reference a function that does not know the name beforehand. These operations are unthinkable in C.
4 There is also a very interesting detail, that is, the effect of type on object behavior is various, for example, a = 1; b = 1 In this statement, in Python, it is possible that a, B is pointing to an object with a value of 1, or to an object with two values of 1, respectively. And for example this statement, C = []; d = [], then C and D are definitely pointing to the different, newly created empty list. No, if it is "c = d = []" this statement? At this point, C and D point to the same list object again. These differences are not in C.
Finally, let's say why Python is slow. The main reason is that the function call overhead is relatively large. Because everything is now an object, contruct and destroy spend too much. Even 1 + 1 are function call, like ' 12′+ ' 45′ to create a third string object, then calls the string obj ' s __add. Can you imagine how fast it gets up?
Lists and arrays
It is always interesting to parse the list in Python and the array in C. Believe that maybe some friends and the same, when the list of beginners, it is used as an array to learn. The initial characterization of the list and array differences was mainly concentrated at two points. First, the list can contain many different types of data, such as
[' This ', 1, ' is ', ' an ', ' array ']
This list, if placed in C, is actually a string array, which is equivalent to two dimensions.
Second, list has a lot of methods, which is itself an object, and this simple array of C is different. The operation of the list is varied because there are methods and overloaded operators. Also brings some problems, such as the following example:
Join us to generate a multidimensional list, using the following statement
A = [[None] * 2] * 3
As a result, the value of a will be
[None, none], [None, none], [None, none]]
Look no problem, a typical two-dimensional array form of the list. OK, now we want to change the value of the first none, using the statement
A[0][0] = 5
Now let's take a look at the value of a:
[5, none], [5, none], [5, none]]
Did you find the problem? This is because when you copy with *, you just create a reference to the object, instead of actually creating it. This creates a list of three references, all of which point to the same 2-length list. A change in one of the rows will be displayed in all rows, which is certainly not what you want. Solution Of course there is, we created this way
A = [none]*3
For I in range (3):
A[i] = [None] * 2
This creates a list that contains three different lengths of 2.
So, it is always stressed that the more complex things, the more flexible, the more prone to error.
Code optimization
C is a very simple language, when we consider optimization, often think very simple, such as the less system-level calls the better (buffer mechanism), eliminate the cycle of inefficient and unnecessary system references, and so on, in fact, is mainly based on the system and hardware details to consider. And Python is completely different, of course, the above-mentioned optimization forms, for Python is still practical, but because of the python syntax, the variety of libraries and modules, so for the language itself, there are a lot of noteworthy optimization points, to give a few examples.
For example, we have a list L1, and want to build a new list l2,l2 including 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])
While the more optimized and graceful version is
L2 = L1[:3]
Another example, if S1. S7 is a large string (10k+), then join ([S1,S2,S3,S4,S5,S6,S7]) is much faster than S1+S2+S3+S4+S5+S6+S7 because the latter is accounting for many second-son expressions, and join () completes all copies in a single process. Also, for string manipulation, use the Replace () method for string objects. Use regular expressions only when there is no fixed string pattern.
So, to optimize as a criterion, if C is short and concise, Python is profound.
Include and import
The include in the C language is very simple, because the form is single, the meaning is clear, when you need to use external functions and other resources, use include. There is a similar mechanism in Python, which is import. At first glance, these two guys are quite alike, not all of us using external resources (the most common is the function or module (Python)) When we use this to indicate? In fact, the basic difference between the two processing mechanisms is that the include in C is used to tell the preprocessor that the contents of the file specified by this include, you have to me as in the local source file appears. And import, it is not simple to insert the contents of the following * directly into the local, this thing more flexible. In fact, almost all similar mechanisms, Python is more flexible than C. This is not to say C is not good, C is concise, I actually prefer C.
Simply talk about this flexibility. Import has three types in Python, import x, from x Import * (or a,b,c ...), X = __import__ (' x '). The most common is the second, because it is more convenient, not like the first one always use X.module to invoke the module. The From X Import * is just import the module of the public (which is generally not named by __), or you can specify a,b,c to import.
When do you use the form? It should be said that in most module documents, you will be told exactly which form you should use. From X Import * may be more appropriate if you need to use many objects, but for now, most third-party Python libraries do not recommend using the FROM modulename import * format. Doing so will confuse the namespace of the introduction. Many people do not use this approach even for modules that are specifically designed for this mode, including Tkinter, threading, and Matplot. And if you just need an object class A, then it's better to use the from X import a than import x.a, because later you call A's function directly with a.function (), without adding X.
What if you don't even know the module you want to import? Note that the advantage of Python is that we can use __import__ (module) to invoke module, where the module is a string, so you can decide at run time what module you want to invoke. As an example:
Def classfrommodule (module, Name):
MoD = __import__ (module)
Return GetAttr (mod, Name)
Here, a function classfrommodule is defined, and you can call it at any time of the code,
o = Classfrommodule (Moduleoftheclass, Nameoftheattribute) ()
Just pass in the string form of the module you want to import Moduleoftheclass and the name of the property Nameoftheattribute (of course, the data can be a method), it can be called, the name string is not specified beforehand, It is judged by the circumstances of the operation.
Incidentally, the order of import in Python also has a default rule, which is somewhat similar to the include in C, because we typically include the system files first, and then include our own header files (and the difference between <> and ""). In Python, you should generally import modules in the following order:
1. Standard library modules-such as SYS, OS, getopt, etc.
2. Third-party modules
3. The locally implemented module.
Global variables
Here we talk about global variables, not that Python and C have different concepts of global variables, and their concepts are the same. There are some differences in the mechanism of use only. As an example:
–module.py–
Globalvar = 1
def func ():
Print Globalvar
# This makes Someglobal ReadOnly,
# Any attempt to write to Someglobal
# would create a new local variable.
Def FUNC2 ():
Global Globalvar
Globalvar = 2
# This allows manipulate the global
# variable
In the Func function, Globalvar is read-only. If you use an assignment such as Globalvar = xxx, Python will recreate a new local object and assign the new value to it, and the original object value will not change. In the FUNC2 function, as we have stated beforehand that the Globalvar is global, the change takes effect directly on the global variable.
Beginner python, feel the difference from C