C programmer's Python Development Summary

Source: Internet
Author: User
Tags sleep function

I have published an article titled how to learn a new language. Later, I began to learn python. The specific reason is not very clear. I started with a concise Python tutorial and wrote two notes, "Python first experience 1" and "Python first experience 2", but I didn't feel much about it. Later, I wanted to try Python because of a small project. In this process, I experienced the simplicity and efficiency of Python and a flying feeling-maybe I am a C language programmer.

Facts once again prove that the best way to learn a new language is to use it in actual development. No one next to me has Python experience, so the learning process is somewhat tortuous. Fortunately, many problems can be solved through the network. In addition, I found that a book "Python Reference Manual" is very good during the learning process, so I have to read it all for a while.

The biggest obstacle to learning a language is not grammar or library usage, but the way of thinking in the previous language. The mindset will make people tend to use new languages to simulate familiar languages, this is the biggest obstacle, and you will not be able to appreciate the advantages of this language. Therefore, we need to learn how to solve problems with new ways of thinking. Let's take a look at this very symbolic metaphor:

This is like you have only one screw head. Someone gave you a screw driver and you said, "Hey, this is not a good one, but I should be able to take a screw driver backwards, use a screwdrivers to smash things." You get a very bad rolling head, but in fact it does have a very good screwdriver. Therefore, you should be open and positive to all things ."

In this regard, LI Yong-hao translated an article titled What is pythonic. The article written by Lai Yonghao in python is very good.

Now, let's get started: Below is my conclusion, which may not be pythonic enough. If you have a better solution, I will point it out.

Socket programming:

1. functions are similar to functions in C. The only difference is that when an error occurs, the function is not notified by the return value, but by triggering an exception. Therefore, the bind, recvfrom, sendto must capture exceptions.

2. the socket is also disabled during garbage collection.

3. Obtain the IP address of the NIC:

S = socket. socket (socket. af_inet, socket. sock_dgram)

Return socket. inet_ntoa (fcntl. IOCTL (S. fileno (), 0x8915, struct. Pack ('256s', Ethname [: 15]) [20: 24])

Use of strings:

1. delete a string. This method is not provided directly, but replace can be implemented as follows:

"Abcdef". Replace ("","")

There is also a method for the same function: translate. Its original function is to replace a character in a string with another character. Note that it is not a string. Its first parameter is a conversion table. The second parameter is the string to be deleted. We can use the second parameter del to implement this function. At the same time, the first parameter is set to none.

Translate may be more efficient. In addition, its second parameter can make a string contain multiple characters, so that multiple characters will be deleted.

2. Strip: removes spaces on both sides of the string and returns a new string. This function is very useful.

3. endswitch: Check whether the string has ended with a string.

4. Partition: it divides a string into three parts based on the specified string and returns a single tuple. The first is to specify the content before the string, the second is to specify the string, and the third is to specify the content after the string. It is very useful for string parsing.

5. Split: Splits a string into multiple substrings according to a specified string, and returns a split list.

6. Join: connect each string in a string list and insert the specified string in the middle.

 

Function usage:

1. Function scope: Define a variable in the function. If it is the same as the global variable, the global variable name will be overwritten, global variables are not changed. However, if you use it directly, global variables are used. At the same time, if you want to modify the global variable, you must specify the global variable: Global.

Dictionary usage:

1. Delete dictionary: Using del dict [k] directly may cause exceptions. First, it is inefficient to determine whether K exists. Using exceptions makes the program structure look bad. A good method is pop (K, default V ). Delete K items and return. If no value exists, the default value V is returned. If the default value is not added, an exception is thrown.

 

2. directly using the dictionary subscript to obtain the dictionary value may lead to an event. If the get method is used, no. If the get method does not exist, none is returned. You can also set a default value that does not exist.

3. Use the dictionary to format the string: Print "value is % (key) S" % kvdict

4. The item method returns a list. The element in the list is a tuples, the first is the key, and the second is the value. Easy to use.


Use of the list:

1. delete a list: You cannot delete a linked list during traversal, which can lead to unpredictable consequences. You can use list filtering to obtain a new list.

2. List Filtering:

DefFilterfun(Node): # This function does two things.

Node. cyclecount = node. cyclecount-1

Return node. cyclecount <0

Timeoutlist = filter (filterfun, timerlist)

Execute the filterfun function on each node in the timerlist. Based on the results returned by filterfun, a new list is formed for the real items.

 

3. MAP: kvlist = map (lambda X: X. Strip (), kvlist)

4,

XML usage:

1. xml. etree. elementtree is a useful module for processing XML message packets.

2. The element executes the XML root node.

3. ELEM. Find (PATH): Find the child node whose path is path under the root node.

4. ELEM. findall (PATH): The same subnode may have multiple subnodes. Here, a list is returned.

5. ELEM. findtext (PATH): Get the content of the child node in the specified path, which is frequently used.

6. ELEM. Get (key); get the attribute value.

7. If it is useless, none is returned.

8. ELEM. append: Add a self-node.

9. ELEM. Tag: return the tag value, that is, name.

10. ELEM. Text: The returned content.

11. ELEM. attrib: returns the attribute dictionary.

12. subelement: generate a node and automatically add it as a child node of the parent node.

13. tostring: convert to an XML text string. But does not include the xml header. If the encoding method is UTF-8 or gb2312, gb2312 will generate the xml header; if it is UTF-8, it will not generate the xml header

14. fromstring: converts a string to an elementtree object. Similar to XML.

15. ELEM. Set (); set the attribute value

Time usage:

1. The time. Sleep () function has the sleep function in C, in seconds, but can accept floating point numbers. This can represent milliseconds.

2. Ti = datetime. datetime. Now () can display the current time, including the current microseconds. The difference between the two values can indicate the interval: microsecondlong = timelong. Seconds * 1000000 + timelong. microseconds. The difference is between seconds and microseconds.

3,

 

OO usage:

1. If you do not want the member variables or methods to be used externally (that is, the private feature), you can activate them with _ double underscores.

2. python can also implement abstract base classes, that is, interfaces:

3. The _ STR _ attribute can convert an object into a string, that is, calling print (object) is a printed string.

4. For details about _ call _, see the object called as a function. You can give it an input parameter.

5. Can object instances be deleted?

6. Check the python reference manual.

Use of modules:

1. If you do not want to use some functions and variables of a module by another module, you can start with a single underline. In this way, import * does not exist, but importmode is used, and mode. _ fun can still be called.

2,

 

Log usage:

1. The standard logging module can basically meet my work requirements.

2. Set log initialization:

Logging. basicconfig (

Filename ="Test. log",

Format ="[% (Asctime) S-% (levelname) S] % (Message) s [% (filename) s, % (lineno) D]",

Level = logging. info,

Datefmt ="% F % t")

3. In addition, a powerful function is the filtering function, which can be used to filter many items such as the level, file, and row number.

4,

 

Introspection:

1. Type () can be used to view the object type. This is introspection. That is, you can see what type you are. This function is very useful in dynamic languages.

2,

 

Use of configuration file reading:

1. Use the configparser module. Example:

Conf = configparser ()

Conf. Read ("Snmp_agent.ini")

 

Print (Conf. Get ("Main","Log_level"))

Print (Conf. getint ("Main","Ne_agent_port"))

Print (Conf. Get ("Main", "ne_agent_qip "))

 

Abnormal use:

1. Try to use less. It makes the program difficult to understand and unpredictable. For example, an exception changes the state of the program to an unknown state.

2. You can find alternative solutions.

3. The program is very important and cannot be stopped. It can be run in the main loop packaging in exception handling.

4. Print the exception information for future positioning: log. Error (traceback. format_exc ())

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.