Liaoche python excerpt two rounds 2

Source: Internet
Author: User
Tags error handling instance method rounds rowcount sqlite database

1>>>defSet_age (self, Age):#define a function as an instance method2... Self.age = Age3 ...4>>> fromTypesImportMethodtype5>>> s.set_age = Methodtype (Set_age, s)#binding a method to an instance6>>> S.set_age (25)#Invoking instance methods7>>> S.age#Test Results825

2, four points to note: 1, classes and instances can dynamically bind properties and methods. Class-bound properties and methods can act on an instance, and vice versa; 2, the class dynamic binding method and the instance binding are different, the binding property is the same class binding property: Student.sex = ' m ' Instance binding property: S.sex = ' m ' class binding method: From types import Me Thodtype def set_sex (self, sex): Self.sex = Sex Student.set_sex = Set_sex Instance binding method: From types import Methodtype def set_sex ( Self, sex): Self.sex = Sex S.set_sex = Methodtype (Set_sex, s) 3,slots You can restrict the properties of classes and instances. With slots restrictions, classes and corresponding instances cannot be arbitrarily dynamically bound to attribute 4,slots is not inheritable. That is, the restriction of the parent class does not inherit to the child class.

3. The biggest difference between dynamic and static languages is the definition of functions and classes, not defined at compile time, but dynamically created at runtime.

4.

Some errors are caused by problems with programming, such as the output of an integer output string, which we often call bug,bug must be fixed.

Some errors are caused by user input, such as letting the user enter an email address, resulting in an empty string, which can be handled by checking user input.

There is a type of error is completely unable to predict during the program running, such as when writing to the file, the disk is full, write not in, or fetch data from the network, the network suddenly broke down. This type of error, also known as an exception, is usually handled in a program, otherwise the program terminates and exits due to various problems.

5.

 1  try   :  2   foo ()  3  except   ValueError as E:  4  print  ( " valueerror  "  Span style= "COLOR: #000000" >)  5  except   Unicodeerror as E:  6  print  ("  unicodeerror   ") 

The second one except is never caught UnicodeError , because UnicodeError ValueError the subclass, if any, is also captured by the first one except .

6, try...except There is a huge advantage of capturing errors, that is, you can cross multiple calls, such as function main() calls, foo() foo() calls, the result is bar() bar() wrong, at this time, as long as the main() capture, you can handle

1 defFoo (s):2     return10/Int (s)3 4 defBar (s):5     returnFoo (s) * 26 7 defMain ():8     Try:9Bar'0')Ten     exceptException as E: One         Print('Error:', E) A     finally: -         Print('finally ...')

In other words, there is no need to catch errors in every possible error, as long as the error is captured at the appropriate level. In this way, it greatly reduces the try...except...finally trouble of writing.

7.

when an error occurs in the program, Python automatically throws an exception, or it can throw an exception by raise the display. Once the raise statement is executed, the statement following the raise cannot be executed.

This is logging the benefit that allows you to specify the level of logging information, there,, and debug info so on warning error several levels, when we specify level=INFO , it logging.debug will not work. Similarly, after the designation level=WARNING , debug and info will not work. This way, you can confidently output different levels of information, do not delete, and finally unified control the output of which level of information.

loggingAnother benefit is that with a simple configuration, a single statement can be output to a different place at the same time, such as the console and the file.

8. Before reading and writing files, we must first understand that the function of reading and writing files on disk is provided by the operating system, the modern operating system does not allow the normal program to operate the disk directly, so the read-write file is requesting the operating system to open a file object (often referred to as a file descriptor), and then Read the data from this file object (read the file) from the interface provided by the operating system, or write the data to the file object (write file).

Most of the time, data read and write is not necessarily a file, but also can read and write in memory.

Stringio, as the name implies, reads and writes STR in memory.

To write Str to Stringio, we need to create a stringio and then write it like a file:

1>>> fromIoImportStringio2>>> f =Stringio ()3>>> F.write ('Hello')455>>> F.write (' ')617>>> F.write ('world!')869>>>Print(F.getvalue ())TenHello world!

Typeerror:initial_value must is Unicode or None, not str error handling ""

response.read()Returns an instance of and is a bytes StringIO in-memory stream for text only. Use BytesIO instead.

From what's new in Python 3.0-text vs. Data Instead of Unicode vs. 8-bit

9.

Bytesio

Stringio operation can only be str, if you want to manipulate binary data, you need to use Bytesio.

Bytesio implements read-write bytes in memory, we create a bytesio and then write some bytes:

10.

Python language-specific serialization modules are pickle , but you can use modules if you want to make serialization more generic and more web-compliant json .

jsonModules dumps() and loads() functions are examples of very well-defined interfaces. When we use it, we only need to pass in a required parameter. However, when the default serialization or deserialization mechanism does not meet our requirements, we can also pass in more parameters to customize the serialization or deserialization rules, not only the interface is simple to use, but also to achieve full scalability and flexibility.

11.

Because Python is cross-platform, nature should also provide a cross-platform, multi-process support. multiprocessingmodules are multi-process modules with cross-platform versions.

multiprocessingThe module provides a Process class to represent a process object

12, in the regular expression, if the character is given directly, it is exact match. You can match a number to match \d \w a letter or a number.

    .can match any character

To match a variable-length character, in a regular expression, with a representation of * any character (including 0), with a representation of + at least one character, representing ? 0 or 1 characters, denoted by {n} n characters, with {n,m} a n-m character

\d{3}\s+\d{3,8}

Let's read from left to right:

    1. \d{3}Indicates a match of 3 digits, for example ‘010‘ ;

    2. \sCan match a space (also including tab and other white space characters), so that \s+ there is at least one space, such as matching ‘ ‘ , ‘ ‘ etc.;

    3. \d{3,8}Represents a 3-8 number, for example ‘1234567‘ .

To make a more accurate match, you can use a [] representation range, such as:

    • [0-9a-zA-Z\_]Can match a number, letter, or underscore;

    • [0-9a-zA-Z\_]+Can match a string of at least one number, letter, or underscore, for example, and ‘a100‘ ‘0_Z‘ ‘Py3000‘ so on;

    • [a-zA-Z\_][0-9a-zA-Z\_]*It can be matched by a letter or underscore, followed by a string consisting of a number, letter, or underscore, which is a valid Python variable;

    • [a-zA-Z\_][0-9a-zA-Z\_]{0, 19}More precisely limit the length of a variable to 1-20 characters (1 characters before + 19 characters later).

A|BCan match A or B, so (P|p)ython you can match ‘Python‘ or ‘python‘ .

^Represents the beginning of a row, ^\d indicating that a number must begin.

$Represents the end of a line, indicating that it \d$ must end with a number.

You may have noticed it, but you can match it, py ‘python‘ but plus ^py$ it turns into an entire line match, it only matches ‘py‘ .

We strongly recommend that you use the Python r prefix without having to consider escaping the problem.

In addition to simply judging whether a match is matched, the regular expression also has the power to extract substrings. The () Grouping (group) to be extracted is represented by the. Like what:

^(\d{3})-(\d{3,8})$Two groups are defined separately, and the area code and local numbers can be extracted directly from the matching string:

In addition to simply judging whether a match is matched, the regular expression also has the power to extract substrings. The () Grouping (group) to be extracted is represented by the. Like what:

^(\d{3})-(\d{3,8})$Two groups are defined separately, and the area code and local numbers can be extracted directly from the matching string:

If a regular expression is to be reused thousands of times, for efficiency reasons, we can precompile the regular expression and then reuse it without compiling this step, directly matching:

1>>>ImportRe2 #Compile:3>>> Re_telephone = Re.compile (r'^ (\d{3})-(\d{3,8}) $')4 #use:5>>> Re_telephone.match ('010-12345'). Groups ()6('010','12345')7>>> Re_telephone.match ('010-8086'). Groups ()8('010','8086')

13.

Because the Internet Protocol contains hundreds of protocol standards, but the most important two protocols are TCP and IP protocol, so everyone put the Internet Protocol referred to as TCP/IP protocol.

Communication, both parties must know each other's identity, such as email must know the other's e-mail address. The unique identity of each computer on the Internet is the IP address, similar 123.123.123.123 . If a computer is connected to two or more networks, such as a router, it will have two or more IP addresses, so the IP address is actually the computer's network interface, usually the NIC.

The IP protocol is responsible for sending data from one computer to another on the network. The data is split into a small piece and then sent out via IP packets. Because of the complexity of the Internet link, there are often multiple lines between the two computers, so the router is responsible for deciding how to forward an IP packet. The IP packet is characterized by the number of routes sent by the block, but not guaranteed to arrive, and not guaranteed in order.

14.

An IP packet contains both the source and destination IP addresses, the source and destination ports, in addition to the data to be transferred.

What does a port do? When communicating with two computers, it is not enough to send only the IP address because there are multiple network programs running on the same computer. After an IP packet comes in, whether it is to the browser or QQ, you need a port number to differentiate. Each network program requests a unique port number for the operating system, so that two processes that establish a network connection between the two computers require their respective IP addresses and their respective port numbers.

A process may also establish links to multiple computers at the same time, so it will request many ports.

Socketwhen created, AF_INET specifies that the IPV4 protocol is used, and if a more advanced IPv6 is used, it is specified as AF_INET6 . SOCK_STREAMspecifies that a stream-oriented TCP protocol is used so that an Socket object is created successfully, but no connection has been established. After establishing the TCP connection, we can send a request to the Sina server and ask to return the contents of the homepage:

# Send data:s.send (b'get/http/1.1\r\nhost:www.sina.com.cn\r\nconnection:close\r\n\r\n' )
# Receive data:buffer = [] while True:    #  receives up to 1k bytes at a time:    d = S.RECV (1024x768)    if  d:        buffer.append (d)    Else:         break= b'. Join (buffer)

When the data is received, the method is called to recv(max) receive a specified number of bytes at a time, so it is received repeatedly in a while loop until the recv() empty data is returned, indicating that the receive is complete and exits the loop.

When we have finished receiving the data, we call the close() method to close the socket so that a complete network communication is over:

Socket programming with the TCP protocol is very simple in Python, for the client, to actively connect to the server's IP and the specified port, for the server, to first listen to the specified port, and then, for each new connection, create a thread or process to process. Typically, the server program will run indefinitely.

The same port, after being bound by a socket, cannot be bound by another socket.

UDP is used similar to TCP, but does not require a connection to be established. In addition, the server-bound UDP port and TCP port do not conflict, that is, UDP 9999 port and TCP 9999 port can be bound separately.

15, in order to facilitate the program to save and read data, but also directly through the conditions to quickly query to the specified data, there is a database of this dedicated to centralized storage and query software

A table is a collection of relational data in a database that usually contains multiple tables, such as a student's table, a class table, a school table, and so on. The table and table are associated by a foreign key.

To operate a relational database, you first need to connect to the database, a database connection called connection;

After connecting to the database, you need to open the cursor, called the cursor, execute the SQL statement through the cursor, and then get the execution result.

Python defines a set of API interfaces for manipulating databases, and any database to be connected to Python requires only a Python-compliant database driver.

#Import SQLite driver:>>>ImportSqlite3#Connect to the SQLite database#The database file is test.db#If the file does not exist, it is automatically created in the current directory:>>> conn = Sqlite3.connect ('test.db')#Create a cursor:>>> cursor =conn.cursor ()#execute an SQL statement to create the user table:>>> Cursor.execute ('CREATE TABLE User (ID varchar () primary key, name varchar )')<sqlite3. Cursor Object at 0x10f8aa260>#continue executing an SQL statement and insert a record:>>> Cursor.execute ('INSERT into user (ID, name) VALUES (\ ' 1\ ', \ ' michael\ ')')<sqlite3. Cursor Object at 0x10f8aa260>#to get the number of rows inserted through ROWCOUNT:>>>Cursor.rowcount1#Close cursor:>>>cursor.close ()#COMMIT TRANSACTION:>>>Conn.commit ()#Close connection:>>> Conn.close ()
1>>> conn = Sqlite3.connect ('test.db')2>>> cursor =conn.cursor ()3 #To execute a query statement:4>>> Cursor.execute ('SELECT * from user where id=?', ('1',))5<sqlite3. Cursor Object at 0x10f8aa340>6 #To obtain a query result set:7>>> values =Cursor.fetchall ()8>>>Values9[('1','Michael')]Ten>>>cursor.close () One>>> Conn.close ()

When using Python's Db-api, you can use it with confidence as long as you are clear Connection and the object is open and you Cursor must remember to close it.

With the object execution, when the statement is executed, the Cursor insert update delete result rowcount of the execution is returned by the number of rows that are affected.

Cursor select When you execute a statement by using an object, featchall() you get a result set. The result set is a list, each element is a tuple, corresponding to a row of records.

When you manipulate a database in Python, you import the corresponding driver for the database, and then Connection manipulate the data through objects and Cursor objects.

To ensure that open Connection objects and Cursor objects are closed correctly, the resource is compromised.

How can you make sure that objects and objects are also closed when an error occurs Connection Cursor ? Please remember try:...except:...finally:... the usage.

Liaoche python excerpt two rounds 2

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.