Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - What in-depth details does Python have that newbies won’t know?
What in-depth details does Python have that newbies won’t know?

It has been more than half a month since I started reading Python. I have read two books: Python Core Programming and DiveintoPython. I read two books in half a month, and everyone knows how much it is to swallow them all. This is also because I have no need to use this for large-scale development for the time being, and it is mainly used for daily small program testing. So my strategy is to browse it as a whole and check it when I need it. It is said that the first edition of Core Programming is too old. It always talks about things before 2.2. The translated electronic version I read is not well translated and is very obscure. After reading this, I was still a little confused. I read online that people said DIP was good, and Woodpecker also had free electronic documents, so I looked for this. How can I put it, it is better than core programming, but it is not suitable for beginners who are watching it for the first time. The reason why I think it is well explained is because some concepts are still a bit vague when looking at core programming. After reading this book, I understand a lot. If you are a beginner, just read this book, it is guaranteed to be difficult to understand. The following are some of the obvious differences between C and python that were summarized in the process of learning and reading the materials, including general directions and details. I definitely haven't finished summarizing it. For example, dynamic functions, lambdas, etc., I am too lazy to write up. In fact, as two completely different languages, the following differences are just the tip of the iceberg. It should be a good idea, at least it should be helpful to friends who have the same research interests as me and are considering whether to learn another language. This article can also be regarded as DIP’s study notes. By the way, if you have friends who know about it, they can help recommend Python teaching materials that are highly practical. It is impossible to learn the language well without lots of practice and just gestures. Purpose of study: My future research direction is embedded. Obviously, C language is my main language. I am not a language enthusiast. I used to think that for people who do research rather than application, it is better to know multiple languages ??than to be proficient in one language. The reason why I went to see python is mainly because python is more conducive to quickly developing some programs, and also because I now realize that research and application cannot be separated. Personally, I think that if you want to gain a foothold in the competition of computer engineering, you must know the C language. Because if you really want to do high-performance programming, you can't leave the machine architecture behind and let the Python virtual machine (or Java virtual machine, etc.) handle all the underlying tasks for you. There are more and more CPU cores and more and more terrifying memory performance bottlenecks. For upper-level developers, it doesn't matter, but for high-performance program developers, these are not transparent. For many applications, it is more effective to control them yourself. In these situations, assembly and C are still irreplaceable. However, just knowing C is not enough. Mastering an object-oriented language, a relatively higher-level language, will not only be beneficial to future personal development, but will also help one's 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 steeper. It seems simple, but in fact it is full of traps. Even a seemingly simple and inefficient program cannot be completed in 1 or 2 months. When it comes to the depth and difficulty of optimization, the required skills are calculated on a yearly basis. But once you have a good foundation in C language, your understanding of computers and other languages ??will be of great benefit. For example, if you have a C foundation, it can be said that after learning python for one day, you can write some short programs. The subsequent optimization is not a big deal with the algorithm, it is just a very basic statement exchange. Of course, this is not to say that Python is not good. In fact, in upper-level applications, Python is not just as convenient as C. Many people think that since they understand C, further mastering C++ should be a matter of course. However, C++ is not a superset of C, and I don’t like the complexity and complexity of C++, so I decided to take a look at Python. I really like the elegance and speed of Python. The language type is different from C. Python is a dynamically typed language and a strongly typed language. How to understand this classification? It can probably be classified according to the following description: statically typed language A language in which the data type is determined during compilation. Most statically typed languages ??ensure this by requiring that the data type of any variable be declared before its use. Java and C are statically typed languages. Dynamically typed language A language that determines data types at runtime, as opposed to static typing. Python is dynamically typed because they determine the type of a variable the first time you assign it a value. Strongly typed language A language that always enforces type definitions. Java and Python are mandatory type definitions. You have an integer and you can't treat it as a string without explicitly converting it. Weakly typed language A language in which types can be ignored, as opposed to strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', which can then be viewed as the integer 123, all without any explicit conversion. How to understand the "dynamically determined variable type" of the object mechanism, we must start with Python's Object object mechanism.

Objects (hereinafter referred to as objects) are Python’s abstraction of data. All data in Python are represented by objects or relationships between objects. Functions are objects, strings are objects, and everything is the concept of an object. Every object has three attributes: entity, type and value. Understanding entities is an important step in understanding objects. Once an entity is created, it will never change or be explicitly destroyed. At the same time, generally speaking, the type (type, including number, string, tuple and others) will not change, only its value may change. If you are looking for a specific explanation, the entity is equivalent to the address of the object in the memory and is its essential existence. Types and values ??are just the external presentation of entities. Then Python provides some interfaces for users to interact with objects, such as the id() function to obtain the integer representation of the object entity (actually the address here), and the type() function to obtain its type. This object mechanism is something that C does not have. It is mainly reflected in the following points: 1. As I just said, C is a static type language. We can define inta, charb, etc., but it must be specified in the source code in advance. For example, we can directly specify a = "lk" anywhere in Python. In this way, the type of a is string. This is determined when it is assigned, and we do not need to write it explicitly in the code. In C, we must explicitly specify char*a = "lk", that is, manually specify the type of a in advance. 2 Since in C, there is no concept of objects, only "representation of data", for example, if there is If we want to compare two int variables a and b, 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 It is essentially a pointer to a string. If you use == to compare directly, 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. This is called "object identity". To compare two string values ??in Java, you use str1.equals(str2). Then in Python, it is different from the previous two. Due to the introduction of objects, we can use the "is" operator to compare the entities of two objects. It has nothing to do with the type of the specific object. For example, your object is Whether tuples, strings, or even classes, you can use "is" to compare, which is essentially a comparison of "object identity", similar to == in Java, and similar to pointer in C. There is also == comparison in Python, which is value comparison. 3. Due to the introduction of the object mechanism, the use of Python is very flexible. For example, we can use the introspection method to view other modules and functions that exist in the form of objects in the memory, obtain their information, and operate on them. In this way, you can define functions without names, call functions out of the order in which they are declared, or even reference functions whose names are not known in advance. These operations are unthinkable in C. 4 There is another very interesting detail, that is, the impact of types on object behavior is in various aspects. For example, in the statement a=1;b=1, what is triggered in Python may be that a and b point to the same value at the same time. The object with a value of 1 may also point to two objects with a value of 1 respectively. For example, in this statement, c=[];d=[], then c and d definitely point to different, newly created empty lists. It's not over, what if it is the statement "c=d=[]"? At this time, c and d point to the same list object again. These differences are not found in c. Finally, let's talk about why python is slow. The main reason is that functioncalloverhead is relatively large. Because everything is now an object, constructing and destroying is also expensive. Even 1+1 is a function call, something like ‘12′+’45′ requires createathirdstringobject, then callsthestringobj’s__add. It is conceivable, how can the speed be increased? Lists and Arrays It's always interesting to analyze lists in Python and arrays in C. I believe some friends may be the same. When they first learned lists, they treated them as arrays. The initial characterization of the difference between lists and arrays mainly focused on two points. First of all, list can contain many different data types, such as ["this",1,"is","an","array"]. If placed in C, this List is actually a string array, which is equivalent to two Well done. Secondly, list has many methods, which itself is an object. This is different from C's simple array. There are many operations on List because there are methods and overloaded operators.

It also brings some problems, such as the following example: if we want to generate a multi-dimensional list, use the following statement A=[[None]*2]*3. As a result, the value of A will be [[None,None],[None ,None],[None,None]] It seems okay at first glance, it is a typical list in the form of a two-dimensional array. Okay, now we want to modify the value of the first None, using the statement A[0][0]=5. Now let’s look at the value of A: [[5,None],[5,None],[5,None ]]Did you find the problem? This is because when you use * to copy, you only create a reference to the object instead of actually creating it. *3 creates a list containing three references, all three references pointing to the same list of length 2. Changes in one row will show up in all rows, which is certainly not what you want. There is of course a solution. We create A=[None]*3foriinrange(3):A[i]=[None]*2. This creates a list containing three different lengths of 2. Therefore, it has always been emphasized that the more complex something is, the more flexible it is and the more error-prone it is. Code optimization C is a very simple language. When we think about optimization, we usually think very simply. For example, the fewer system-level calls the better (buffer mechanism), eliminating the inefficiency of loops and unnecessary system references, Wait, in fact, it is mainly based on system and hardware details. Python is completely different. Of course, the optimization forms mentioned above are still practical for Python. However, because Python’s syntax forms are so different and its libraries and modules are diverse, there is a lot worth noting about the language itself. Let’s give a few examples of optimization points. For example, we have a listL1 and want to build a new listL2. L2 includes the first 4 elements of L1. According to the most direct idea, the code should be L2=[]foriinrange[3]:L2.append(L1[i]) and the more optimized and beautiful version is L2=L1[:3]. For example, if s1..s7 is a large string (10K+), then join([s1,s2,s3,s4,s5,s6,s7]) will be much faster than s1+s2+s3+s4+s5+s6+s7, because the latter Subexpressions are evaluated many times, while join() completes all copies in one pass. Also, for string operations, use the replace() method on string objects. Use regular expressions only when there is no fixed string pattern. Therefore, using optimization as the criterion, if C is short and concise, Python is broad and profound. include and import. Include in C language is very simple, because the form is single and the meaning is clear. When you need to use resources such as external functions, use include. There is a similar mechanism in Python, which is import. At first glance, these two guys are quite similar. Don’t we use this to indicate when we want to use external resources (the most common ones are functions or modules (Python))? In fact, it is not the case. The essential difference between the two processing mechanisms is that include in C is used to tell the preprocessor that the contents of the file specified by this include are regarded as appearing in the local source file. As for import, it is not simply inserting the following content *directly* into the local. This thing is more flexible. In fact, Python is more flexible than C for almost all similar mechanisms. This is not to say that C is not good. C is very concise. I actually prefer C. Let’s talk briefly about this flexibility. Import has three forms in python, importX, fromXimport*(ora,b,c...),X=__import__('x'). The most commonly used one is the second one, because it is more convenient and does not always use X.module to call the module like the first one. fromXimport* only imports public modules (generally modules not named with __). You can also specify a, b, c to import. When to use which form? It should be said that in most module documentation, you will be clearly told which form should be used. If you need to use many objects, then fromXimport* may be more suitable. However, at present, most third-party Python libraries do not recommend using the frommodulenameimport* format. Doing so will clutter the introducer's namespace. Many people don't even do this with modules designed specifically for this mode (including Tkinter, threading, and matplot). And if you only need a certain object class a, then using fromXimporta is better than using importX.a, because in the future, when you call the function of a, you can directly use a.function() without adding X.

What if you don't even know the module you want to import? Please note that the advantages of Python are reflected at this time. We can use __import__(module) to call the module, where the module is a string. In this way, you can decide at runtime what module you want to call. For example: defclassFromModule(module,Name):mod=__import__(module)returngetattr(mod,Name) Here, a function classFromModule is defined, you can call it at any time in the code, o=classFromModule(ModuleOfTheClass,NameOfTheAttribute)( ) You only need to pass in the module ModuleOfTheClass you want to import and the name of the attribute NameOfTheAttribute in the form of a string (of course it can be data or a method), and you can call it. This name string does not need to be specified in advance, but is based on what is running at the time. to judge based on the situation. By the way, the order of import in Python also has default rules. This is somewhat similar to include in C, because we usually include system files first, and then include our own header files (and there is a difference with ""). In Python, modules should generally be imported in the following order: 1. Standard library modules—such as sys, os, getopt, etc. 2. Third-party modules 3. Locally implemented modules. Global variables When talking about global variables here, it does not mean that the concepts of global variables in Python and C are different. Their concepts are the same. There are some differences only in the usage mechanism. For example: –module.py –globalvar=1deffunc():printglobalvar#Thismakessomeglobalreadonly,#anyattempttowritetosomeglobal#wouldcreatenewlocalvariable.deffunc2():globalglobalvarglobalvar=2#thisallowsyoutomanipulatetheglobal#variable In the func function, globalvar is read-only. If you use an assignment statement such as globalvar=xxx, Python will recreate a new local object and assign the new value to it, and the original object value will remain unchanged. In the func2 function, since we have declared in advance that globalvar is global, the changes at this time will take effect directly on the global variable.